Example #1
0
        private void CheckDouble(DoubleColor color)
        {
            btnBlack.Visible   = false;
            btnRed.Visible     = false;
            btnCollect.Visible = false;
            cardImage.Image    = ImageHelper.GetCardImage(_currentCard);
            bool isWin = ResultHelper.IsDoubleWin(color, _currentCard.Color);

            if (isWin)
            {
                WinAmount *= 2;
            }
            else
            {
                WinAmount = 0;
            }

            if (!isWin)
            {
                btnClose.Visible = true;
            }
            else
            {
                TaskEx.Delay(1500).Wait();
                btnBlack.Visible   = true;
                btnRed.Visible     = true;
                btnCollect.Visible = true;
                _currentCard       = CardGenerator.GetRandomCard();
                cardImage.Image    = ImageHelper.Background;
            }

            lblWinAmount.Text = "Win: " + WinAmount;
        }
Example #2
0
 public Primitive()
 {
     // Define material properties
     // TODO: Make material representation to share between primitives, possibly with texture mapping
     Emission    = DoubleColor.Black;
     Diffuse     = DoubleColor.Black;
     _Specular   = DoubleColor.Black;
     _Refraction = DoubleColor.Black;
     Shininess   = 100;
 }
        public void UpdateBarColor(
            DoubleColor begin,
            DoubleColor end
            )
        {
            m_isGradient = true;

            m_begin = begin.ToColor();
            m_end   = end.ToColor();;

            UpdateImage();
        }
Example #4
0
        public static TreeNode CreateColor(DoubleColor color, string name)
        {
            TreeNode node = Create($"{name} (Color {color}):", name);

            node.Tag = color;

            node.Nodes.Add($"r: {color.R}");
            node.Nodes.Add($"g: {color.G}");
            node.Nodes.Add($"b: {color.B}");
            node.Nodes.Add($"Luminance: {color.Luminance}");

            return(node);
        }
Example #5
0
        /// <summary>
        /// Calculate the final color output for a pixel.
        /// </summary>
        /// <param name="back">The background color.</param>
        /// <param name="backA">The background alpha value.</param>
        /// <param name="exposure">The exposure used to brighten the image.</param>
        public int GetOutput(DoubleColor back, double backA, double exposure)
        {
            if (Samples == 0)
            {
                return(GetColorCode(back.R * exposure, back.G * exposure, back.B * exposure, backA));
            }

            /* Attempt at making transparent misses work correctly,
             * currently output is way too dark.
             *
             * double total = samples + misses;
             * //double colorMult = exposure / samples;
             * double transparent = 1 - backA;
             * double colorMult = exposure / (samples + (misses * transparent));
             *
             * double r = color.R * colorMult;
             * double g = color.G * colorMult;
             * double b = color.B * colorMult;
             * double a = 1;
             *
             * double backAlphaAmt = misses / total;
             * double backAmt = backAlphaAmt * backA;
             * backAlphaAmt *= 1 - Math.Min(DoubleColor.GetLuminance(r, g, b) * transparent, 1);
             *
             * r += (back.R - r) * backAmt;
             * g += (back.G - g) * backAmt;
             * b += (back.B - b) * backAmt;
             * a += (backA - a) * backAlphaAmt;*/

            double total     = Samples + Misses;
            double colorMult = exposure / Samples;

            double r = Color.R * colorMult;
            double g = Color.G * colorMult;
            double b = Color.B * colorMult;
            double a = 1;

            double backAlphaAmt = Misses / total;
            double backAmt      = backAlphaAmt * backA;

            r += (back.R - r) * backAmt;
            g += (back.G - g) * backAmt;
            b += (back.B - b) * backAmt;
            a += (backA - a) * backAlphaAmt;

            return(GetColorCode(r,
                                g,
                                b,
                                a));
        }
Example #6
0
        public void Render()
        {
            while (Running)
            {
            }

            Running = true;

            while (!Stop)
            {
                for (uint pixel = 0; pixel < Pixels.Length && !Stop; pixel++)
                {
                    PixelPos pos = Pixels[pixel];

                    for (int i = 0; i < 1; i++)
                    {
                        DoubleColor color = GetColor(pos.X, pos.Y);

                        if (color == DoubleColor.Placeholder)
                        {
                            FullRaytracer.AddMiss(pos);
                        }
                        else
                        {
                            FullRaytracer.AddSample(pos, color);
                        }

                        Samples++;
                    }

                    if (!Stop && FullRaytracer.IsPaused)
                    {
                        Paused = true;
                        FullRaytracer.WaitForResume();
                        Paused = false;
                    }
                }
            }

            Stop    = false;
            Running = false;
        }
        protected DoubleColor GetDoubleColor(
            ColorWheelBase wl,
            double degree,
            double currentRadius,
            double gradRadius
            )
        {
            DoubleColor val;
            AHSL        hsl;
            DoubleColor dc = wl.GetColor(degree);

            switch (PaintMethod)
            {
            case WheelPaintMethod.Brightness:
                val = dc.ToAHSB().Alter(null, 1.0, currentRadius / gradRadius).Double();
                break;

            case WheelPaintMethod.InverseLuminance:
                hsl           = dc.ToAHSL();
                hsl.Luminance = currentRadius / gradRadius;
                val           = hsl.Double();
                break;

            case WheelPaintMethod.Luminance:
                hsl           = dc.ToAHSL();
                hsl.Luminance = 1.0 - currentRadius / gradRadius;
                val           = hsl.Double();
                break;

            case WheelPaintMethod.Saturation:
                val = dc.ToAHSB().Alter(null, currentRadius / gradRadius).Double();
                break;

            default:
                throw new NotImplementedException();
            }

            return(val);
        }
Example #8
0
 public static bool IsDoubleWin(DoubleColor color, CardColor cardColor)
 {
     return((color == DoubleColor.Black && (cardColor == CardColor.Spades || cardColor == CardColor.Clubs)) || (color == DoubleColor.Red && (cardColor == CardColor.Hearts || cardColor == CardColor.Diamonds)));
 }
Example #9
0
 /// <summary>
 /// Adds a hit sample to the pixel.
 /// </summary>
 /// <param name="sample">The color to be added.</param>
 public void AddSample(DoubleColor sample)
 {
     Color += sample;
     Samples++;
 }
Example #10
0
 public SampleSet(DoubleColor color, uint samples, uint misses)
 {
     Color   = color;
     Samples = samples;
     Misses  = misses;
 }
Example #11
0
 /// <summary>
 /// Calculate the final color output for a pixel and convert to a .NET <see cref="System.Drawing.Color"/>.
 /// </summary>
 /// <param name="back">The background color.</param>
 /// <param name="backA">The background alpha value.</param>
 /// <param name="exposure">The exposure used to brighten the image.</param>
 public System.Drawing.Color GetColor(DoubleColor back, double backA, double exposure)
 {
     return(System.Drawing.Color.FromArgb(GetOutput(back, backA, exposure)));
 }
Example #12
0
        public Menu                             //Конструктор: Создаем меню
            (string[] title,                    //заголовок меню
            string[][] items,                   //элементы меню
            string menuinput          = null,   //текст перед полем ввода
            int itemsvisible          = 0,      //кол-во отображаемых пунктов основного меню
            DoubleColor[] colorscheme = null)   //цветовая схема меню
        {
            //проверка на адекватность входных данных
            if (title.Length != items.Length)
            {
                Console.WriteLine("\nОшибка в меню. Несоответствие кол-ва заголовков и доп. меню");
                Console.ReadKey(true);
                Environment.Exit(-2);
            }

            //выделение памяти
            _MenuTitle     = new string[title.Length];
            _Items         = new string[title.Length][];
            _NumberOfItems = new int[title.Length];
            _CurrentItem   = new int[title.Length];
            _PrevItem      = new int[title.Length];
            _ColorScheme   = new DoubleColor[title.Length];
            _MenuWidth     = new int[title.Length];
            _FirstItemY    = new int[title.Length];

            //сохранение данных
            _NumberOfMenus = title.Length;  //кол-во меню
            title.CopyTo(_MenuTitle, 0);    //сохраним заголовки всех меню
            _MenuInputText = menuinput;     //сохраним подпись у поля ввода
            _Input         = "";            //само поле ввода пока пустое

            //определим, показывать ли все пункты основного меню, и сколько их показывать, если нет
            if (itemsvisible <= 0)
            {
                _ItemsVisible = items[0].Length;
                _ShowAllItems = true;
            }
            else
            {
                _ItemsVisible = itemsvisible;
                _ShowAllItems = false;
            }

            for (int i = 0; i < title.Length; i++)
            {
                //выделим память под пункты меню и сохраним их
                _Items[i] = new string[items[i].Length];
                items[i].CopyTo(_Items[i], 0);

                _NumberOfItems[i] = items[i].Length;    //кол-во пунктов меню

                //сохраним цветовую схему меню
                if (colorscheme != null)
                {
                    _ColorScheme[i] = new DoubleColor(colorscheme[i].Text, colorscheme[i].Background);
                }
                else
                {
                    _ColorScheme[i] = new DoubleColor();
                }

                //определение ширины меню (берем максимальную длину строки)
                _MenuWidth[i] = TitleIndent + _MenuTitle[i].Length;
                if (i == 0 && _MenuInputText != null)   //для основного меню учтем поле ввода, если оно есть
                {
                    _MenuWidth[i] =
                        (_MenuWidth[i] < _MenuInputText.Length) ?
                        _MenuInputText.Length :
                        _MenuWidth[i];
                }
                for (int j = 0; j < _Items[i].Length; j++)
                {
                    _MenuWidth[i] =
                        (_MenuWidth[i] < _Items[i][j].Length) ?
                        _Items[i][j].Length :
                        _MenuWidth[i];
                }

                //определение размера поля ввода
                if (i == 0 && _MenuInputText != null)   //если оно есть
                {
                    _InputMaxLength = _MenuWidth[i] - _MenuInputText.Length - 1;
                    if (_InputMaxLength < 5)                         //сделаем так, чтобы поле ввода было не короче 5 символов
                    {
                        _MenuWidth[i]   = _MenuInputText.Length + 6; //если нужно, увеличим ширину меню
                        _InputMaxLength = 5;
                    }
                }

                //определим номера строк экрана для первых пунктов каждого меню, отображаемых на экране
                if (i == 0)     //для основного меню
                {
                    if (_MenuInputText == null)
                    {
                        _FirstItemY[i] = 2;                         //если у основного меню поля ввода нет, то 2 строка
                    }
                    else
                    {
                        _FirstItemY[i] = 4;                         //а если есть, то 4-я
                    }
                }
                else if (i == 1)                                                    //для первого доп. меню
                {
                    _FirstItemY[i] = _FirstItemY[i - 1] + _ItemsVisible + 4;        //отталкиваемся от данных по основному меню с учетом кол-ва отображаемых пунктов
                }
                else                                                                //для остальных доп. меню
                {
                    _FirstItemY[i] = _FirstItemY[i - 1] + _Items[i - 1].Length + 4; //отталкиваемся от данных по предыдущим меню
                }
            }

            _FirstItemVisible = 0;  //первый видимый пункт пока первый
        }
        public void UpdateColor(
            Color color
            )
        {
            DoubleColor c = color.Double();

            if (!String.IsNullOrEmpty(SliderColorComponent))
            {
                DoubleColor begin;
                DoubleColor end;

                m_isGradient = true;

                switch (SliderColorComponent.ToLower())
                {
                case "r":
                    begin = c.Alter(0);
                    end   = c.Alter(255);
                    break;

                case "g":
                    begin = c.Alter(null, 0);
                    end   = c.Alter(null, 255);
                    break;

                case "b":
                    begin = c.Alter(null, null, 0);
                    end   = c.Alter(null, null, 255);
                    break;

                case "alpha":
                case "a":
                    begin = c.Alter(null, null, null, 0);
                    end   = c.Alter(null, null, null, 255);
                    break;

                case "saturation":
                case "sat":
                    begin = c.ToAHSB().Alter(null, 0).Double();
                    end   = c.ToAHSB().Alter(null, 1).Double();
                    break;

                case "brightness":
                case "bri":
                    begin = c.ToAHSB().Alter(null, null, 0).Double();
                    end   = c.ToAHSB().Alter(null, null, 1).Double();
                    break;

                case "hue":
                    m_calc       = (double loc) => ColorWheel.GetColor(loc);
                    m_isGradient = false;
                    begin        = c;
                    end          = c;
                    break;

                default:
                    Debug.Assert(false);

                    begin = Colors.Yellow.Double();
                    end   = Colors.Green.Double();
                    break;
                }

                if (m_begin != begin.ToColor() || m_end != end.ToColor())
                {
                    m_begin = begin.ToColor();
                    m_end   = end.ToColor();

                    UpdateImage();
                }
            }
        }
Example #14
0
        private DoubleColor GetColor(Ray ray, ref DebugRay[] debug)
        {
            Hit         prevHit = default;
            Hit         hit     = default;
            DoubleColor tint    = new DoubleColor(1);

            for (int i = 0; i <= Scene.Recursion; i++)
            {
                // Periodically normalize the direction vector to prevent compounding error
                if (i % 3 == 0)
                {
                    ray = Ray.Directional(ray.Origin, ray.Direction);
                }

                hit = Scene.RayTrace(ray, prevHit);

                DebugRay debugRay = debug != null ? debug[i] = new DebugRay()
                {
                    Hit = hit
                } : null;

                if (hit == default)
                {
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.Missed;
                    }

                    // Return emission or -1 for instant misses
                    if (i == 0)
                    {
                        return(DoubleColor.Placeholder);
                    }

                    // Return miss color for misses
                    return(Scene.AmbientRGB);
                }

                if (Scene.DebugGeom)
                {
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.Debug;
                    }

                    return(hit.Primitive.Specular + hit.Primitive.Diffuse + hit.Primitive.Emission);
                }

                if (i >= Scene.Recursion)
                {
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.RecursionComplete;
                    }
                    break;
                }

                Ray outRay = Ray.Zero;

                Vec4D roughNormal = RandomShine(hit.Normal, hit.Primitive.Shininess);

                double diffLum = hit.Primitive.Diffuse.Luminance;
                double specLum = hit.Primitive.Specular.Luminance;
                double refrLum = hit.Primitive.Refraction.Luminance;
                double emisLum = hit.Primitive.Emission.Luminance;

                double cos      = -roughNormal.Dot(ray.Direction);
                double cosOut   = 0;
                double iorRatio = 0;

                // Calculate ratio of reflection to transmission on this hit
                if ((refrLum > 0 | specLum > 0) && hit.Primitive.RefractiveIndex != 0 && cos >= 0)
                {
                    double iorIn;
                    double iorOut;

                    if (hit.Inside)
                    {
                        iorIn  = hit.Primitive.RefractiveIndex;
                        iorOut = Scene.AirRefractiveIndex;
                    }
                    else
                    {
                        iorIn  = Scene.AirRefractiveIndex;
                        iorOut = hit.Primitive.RefractiveIndex;
                    }

                    iorRatio = iorIn / iorOut;
                    double sinOut = iorRatio * Math.Sqrt(1 - (cos * cos));

                    // Skip refraction when we get total internal reflection
                    if (sinOut >= 1)
                    {
                        refrLum = 0;

                        if (debugRay != null)
                        {
                            debugRay.FresnelRatio = 1;
                        }
                    }
                    else
                    {
                        cosOut = Math.Sqrt(1 - (sinOut * sinOut));
                        double ratioSWave = ((iorOut * cos) - (iorIn * cosOut)) / ((iorOut * cos) + (iorIn * cosOut));
                        double ratioPWave = ((iorIn * cos) - (iorOut * cosOut)) / ((iorIn * cos) + (iorOut * cosOut));
                        double ratio      = ((ratioSWave * ratioSWave) + (ratioPWave * ratioPWave)) / 2;
                        specLum *= ratio;
                        refrLum *= 1 - ratio;

                        if (debugRay != null)
                        {
                            debugRay.FresnelRatio = ratio;
                        }
                    }
                }
                else
                {
                    refrLum = 0;
                }

                double totalLum = diffLum + specLum + refrLum + emisLum;

                if (totalLum <= 0)
                {
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.PureBlack;
                    }
                    break;
                }

                if (i >= Scene.Recursion)
                {
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.RecursionComplete;
                    }
                    break;
                }

                DoubleColor newTint = DoubleColor.Black;
                double      rayRand = Rand.NextDouble() * totalLum;

                // Choose whether to do a specular bounce based on brightness of specular
                if (refrLum != 0 && (rayRand -= refrLum) <= 0)
                {
                    // Transmission implementation
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.Transmitted;
                    }

                    Vec4D outDir = (roughNormal * -cosOut) + ((ray.Direction + (roughNormal * cos)) * iorRatio);
                    outRay  = new Ray(hit.Position, outDir);
                    newTint = hit.Primitive.Refraction;

                    // Only tint on entering the object, and don't count the recursivity
                    if (hit.Inside)
                    {
                        newTint = new DoubleColor(1);
                    }
                }
                else if (specLum != 0 && (rayRand -= specLum) <= 0)
                {
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.SpecularFail;
                    }

                    // Specular reflection
                    Vec4D outDir = Reflection(roughNormal, ray.Direction, cos);

                    // Determine whether the rough normal reflection is heading outward before continuing
                    if (outDir.Dot(hit.Normal) > 0)
                    {
                        if (debugRay != null)
                        {
                            debugRay.Type = BounceType.Specular;
                        }

                        outRay  = new Ray(hit.Position, outDir);
                        newTint = hit.Primitive.Specular;
                    }
                }
                else if (diffLum != 0 && (rayRand -= diffLum) <= 0)
                {
                    // Diffuse reflection
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.Diffuse;
                    }

                    double z     = (2 * Math.Acos(Rand.NextDouble())) / Math.PI;
                    double theta = Rand.NextDouble() * Math.PI * 2;
                    outRay  = new Ray(hit.Position, Vec4D.CreateHorizon(hit.Normal, z, theta));
                    newTint = hit.Primitive.Diffuse;
                }
                else
                {
                    // Emission
                    if (debugRay != null)
                    {
                        debugRay.Type = BounceType.Emission;
                    }

                    Util.Assert(hit.Primitive.Emission != DoubleColor.Black, "Emission being returned with no luminance");

                    // Break out of the loop to return emission early
                    break;
                }

                if (outRay == Ray.Zero)
                {
                    break;
                }

                prevHit = hit;
                ray     = outRay;
                // Since we limit the total brightness of the reflection through our bounce selection above,
                // normalize to the total luminosity of our combined luminosities
                newTint = newTint * Math.Max(totalLum, 1);

                tint = tint * newTint;

                //color = color.add(hit.Primitive.Emission.mult(tint));
            }

            return(tint * hit.Primitive.Emission);
        }
Example #15
0
 /// <summary>
 /// Add a sample to the specified pixel.
 /// </summary>
 /// <param name="pos">The pixel position to add the sample to.</param>
 /// <param name="color">The color of the sample.</param>
 public void AddSample(PixelPos pos, DoubleColor color)
 {
     SampleSets[pos.X, pos.Y].AddSample(color);
 }
        ///
        /// <summary>
        /// Draw all color pointers for palette</summary>
        ///
        protected void DrawPointers(
            )
        {
            int    radius    = (int)Radius;
            double ewidth    = COLOR_POINTER_DIAMETER;
            double pinradius = ewidth / 2;

            if (Palette != null)
            {
                double   gradRadius = ValueRadius;
                double[] angles     = new double[Palette.Colors.Count];

                double[]      radCoff     = new double[Palette.Colors.Count];
                DoubleColor[] wheelColors = new DoubleColor[Palette.Colors.Count];

                for (int i = 0; i < angles.Length; ++i)
                {
                    PaletteColor pc   = Palette.Colors[i];
                    double       coff = 1;

                    switch (PaintMethod)
                    {
                    case WheelPaintMethod.Brightness:
                        coff = pc.DoubleColor.ToAHSB().Brightness;
                        var c = pc.DoubleColor.ToAHSB();
                        c.Saturation   = 1.0;
                        wheelColors[i] = c.Double();
                        break;

                    case WheelPaintMethod.InverseLuminance:

                        coff = pc.DoubleColor.ToAHSL().Luminance;
                        var c1 = pc.DoubleColor.ToAHSL();
                        c1.Saturation  = 1.0;
                        wheelColors[i] = c1.Double();
                        break;

                    case WheelPaintMethod.Saturation:
                        coff = pc.DoubleColor.Saturation;
                        var c2 = pc.DoubleColor.ToAHSB();
                        c2.Brightness  = 1.0;
                        wheelColors[i] = c2.Double();
                        break;

                    case WheelPaintMethod.Luminance:
                        coff = 1.0 - pc.DoubleColor.ToAHSL().Luminance;
                        var c3 = pc.DoubleColor.ToAHSL();
                        c3.Saturation  = 1.0;
                        wheelColors[i] = c3.Double();
                        break;

                    default:
                        throw new NotImplementedException();
                    }

                    angles[i]  = Wheel.GetAngle(pc.DoubleColor);
                    radCoff[i] = coff;
                }

                if (m_schemaElements == null || m_schemaElements.Length != angles.Length)
                {
                    if (m_schemaElements != null)
                    {
                        foreach (Line l in m_lines)
                        {
                            canvas.Children.Remove(l);
                        }

                        foreach (ColorPinpoint e in m_schemaElements)
                        {
                            canvas.Children.Remove(e);
                        }
                    }

                    m_schemaElements = new ColorPinpoint[angles.Length];
                    m_lines          = new Line[angles.Length];

                    for (int i = 0; i < m_schemaElements.Length; ++i)
                    {
                        m_schemaElements[i] = new ColorPinpoint()
                        {
                            Opacity          = 0.9,
                            IsHitTestVisible = true,
                            // Width            = ewidth,
                            Height       = ewidth,
                            CurrentColor = Colors.Black,
                            Tag          = i,
                            PaletteColor = Palette.Colors[i]
                        };

                        m_schemaElements[i].SetValue(Canvas.ZIndexProperty, COLOR_POINTER_ZORDER);
                        m_schemaElements[i].SetValue(ToolTipService.ToolTipProperty, Palette.Colors[i].Name);

                        canvas.Children.Add(m_schemaElements[i]);

                        m_lines[i] = new Line()
                        {
                            Opacity         = 0.0,
                            StrokeThickness = 2,
                            Stroke          = Colors.Black.ToBrush()
                        };

                        m_lines[i].SetValue(Canvas.ZIndexProperty, COLOR_LINE_ZORDER);
                        canvas.Children.Add(m_lines[i]);

                        if (i == 0)
                        {
                            m_main        = m_schemaElements[i];
                            m_main.IsMain = true;
                            SetMainPointEvents(m_main);
                        }
                        else
                        {
                            SetSecondaryPointEvents(m_schemaElements[i]);
                        }
                    }
                }

                for (int i = 0; i < m_schemaElements.Length; ++i)
                {
                    double angle = Wheel.FixAngle(angles[i] - m_angleShift);
                    double rad   = MathEx.ToRadians(angle);
                    double coff  = radCoff[i];

                    double x = Math.Cos(rad) * (gradRadius - pinradius) * coff + radius;
                    double y = -Math.Sin(rad) * (gradRadius - pinradius) * coff + radius;

                    AHSB hsb = Palette.Colors[i].Color;

                    x -= pinradius;
                    y -= pinradius;

                    m_schemaElements[i].SetValue(Canvas.LeftProperty, x);
                    m_schemaElements[i].SetValue(Canvas.TopProperty, y);
                    m_schemaElements[i].CurrentColor = hsb.Double().ToColor();

                    m_lines[i].X1 = radius;
                    m_lines[i].Y1 = radius;

                    m_lines[i].X2 = x + pinradius;
                    m_lines[i].Y2 = y + pinradius;
                }
            }
        }