public void VerifyAllEnums()
 {
     var acceleration = new Acceleration(1, AccelerationUnit.BaseUnit);
     var angle = new Angle(1, AngleUnit.BaseUnit);
     var angularAcceleration = new AngularAcceleration(1, AngularAccelerationUnit.BaseUnit);
     var area = new Area(1, AreaUnit.BaseUnit);
     var density = new MassDensity(1, MassDensityUnit.BaseUnit);
     var electricCurrent = new ElectricCurrent(1, ElectricCurrentUnit.BaseUnit);
     var electricResistance = new ElectricResistance(1, ElectricResistanceUnit.BaseUnit);
     var electricVoltage = new ElectricPotential(1, ElectricPotentialUnit.BaseUnit);
     var energy = new Energy(1, EnergyUnit.BaseUnit);
     var force = new Force(1, ForceUnit.BaseUnit);
     var frequency = new Frequency(1, FrequencyUnit.BaseUnit);
     var jerk = new Jerk(1, JerkUnit.BaseUnit);
     var length = new Length(1, LengthUnit.BaseUnit);
     var mass = new Mass(1, MassUnit.BaseUnit);
     var massFlowRate = new MassFlowRate(1, MassFlowRateUnit.BaseUnit);
     var momentum = new Momentum(1, MomentumUnit.BaseUnit);
     var numeric = new Numeric(1, NumericUnit.BaseUnit);
     var power = new Power(1, PowerUnit.BaseUnit);
     var pressure = new Pressure(1, PressureUnit.BaseUnit);
     var speed = new Speed(1, SpeedUnit.BaseUnit);
     var temperature = new Temperature(1, TemperatureUnit.BaseUnit);
     var time = new Time(1, TimeUnit.BaseUnit);
     var torque = new Torque(1, TorqueUnit.BaseUnit);
     var volume = new Volume(1, VolumeUnit.BaseUnit);
     var volumetricFlowRate = new VolumetricFlowRate(1, VolumetricFlowRateUnit.BaseUnit);
 }
Ejemplo n.º 2
0
 public void NumericConstructorTest1()
 {
     NumericTypes type = new NumericTypes(); // TODO: Initialize to an appropriate value
     Nullable<int> precision = new Nullable<int>(); // TODO: Initialize to an appropriate value
     Numeric target = new Numeric(type, precision);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Ejemplo n.º 3
0
        public AddDigitOperationLine(Numeric number1, Numeric number2, Numeric orderOfMagnitude)
        {
            this.OrderOfMagnitude = orderOfMagnitude;
            var digit1 = number1.GetDigitAtMagnitude(orderOfMagnitude);
            var digit2 = number2.GetDigitAtMagnitude(orderOfMagnitude);

            var newDigit1 = number1.GetCompatibleNumber(digit1.Symbol);
            var newDigit2 = number2.GetCompatibleNumber(digit2.Symbol);
            var result = newDigit1.Clone();
            result.HasAddition().Add(newDigit2);

            this.Digit1 = digit1.Symbol;
            this.Digit2 = digit2.Symbol;
            this.ResultDigit = result.ZerothDigit.Value.Symbol;
            if(result.ZerothDigit.NextNode != null)
            {
                this.CarryDigit = result.ZerothDigit.NextDigit().Value.Symbol;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// pads numeric format with spaces.  if no format function provided, format
        /// defaults to Simple
        /// </summary>
        /// <param name="thisNumeric"></param>
        /// <param name="maxWholeNumberLength"></param>
        /// <param name="maxDecimalLength"></param>
        /// <returns></returns>
        public static string DecimalAlignFormat(this INumeric thisNumeric,
      Numeric maxWholeNumberLength,
            Numeric maxDecimalLength,
            Func<INumeric, string> format = null
        )
        {
            if (thisNumeric == null)
                throw new ArgumentNullException("thisNumeric");

            Func<INumeric, string> actualFormat = (x) =>
            {
                return thisNumeric.GetSimpleFormat();
            };

            if (format != null)
                actualFormat = format;

            string val = actualFormat(thisNumeric);

            Numeric eachWholeNumberLength = null;
            Numeric eachDecimalLength = null;
            thisNumeric.GetNumericLengths(out eachWholeNumberLength, out eachDecimalLength);

            var postPadLength = maxWholeNumberLength.Clone().HasAddition();
            postPadLength.Subtract(eachWholeNumberLength);

            var prePadLength = maxDecimalLength.Clone().HasAddition();
            prePadLength.Subtract(eachDecimalLength);

            postPadLength.PerformThisManyTimes(x =>
            {
                val = " " + val;
            });

            prePadLength.PerformThisManyTimes(x =>
            {
                val = val + " ";
            });
            return val;
        }
Ejemplo n.º 5
0
        public static void TruncateToDecimalPlaces(this INumeric thisNumber,
            Numeric places)
        {
            if (thisNumber == null)
                throw new ArgumentNullException("thisNumber");

            if (places == null)
                throw new ArgumentNullException("places");

            var currPlaces = thisNumber.GetDecimalPlaces();
            if (currPlaces.IsGreaterThan(places))
            {
                var addy = currPlaces.HasAddition();
                addy.Subtract(places);

                addy.PerformThisManyTimes(x =>
                {
                    thisNumber.DoWhileMutable(y =>
                    {
                        y.RemoveFirst();
                    });
                });
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the curve parameter for the given curve length (for length-parameterized splines).
        /// </summary>
        /// <param name="length">The length.</param>
        /// <param name="maxNumberOfIterations">
        /// The maximum number of iterations which are taken to compute the length.
        /// </param>
        /// <param name="tolerance">
        /// The tolerance value. This method will return an approximation of the precise parameter. The
        /// absolute error will be less than this tolerance.
        /// </param>
        /// <returns>The parameter at which the curve has the given length.</returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="tolerance"/> is negative or 0.
        /// </exception>
        /// <remarks>
        /// <para>
        /// This method assumes that the spline is length-parameterized; This means: The parameter of a
        /// key is equal to the length of the spline at this key. If this is not the case,
        /// <see cref="ParameterizeByLength"/> can be called to correct the key parameters
        /// automatically.
        /// </para>
        /// <para>
        /// Normally, the spline curve parameter is not linearly proportional to the length. Therefore,
        /// if the point at a given curve length is required, this method can be used to compute the
        /// curve parameter which will return the point for the given distance. The result of this
        /// method can be used in <see cref="GetPoint"/>.
        /// </para>
        /// <para>
        /// This method uses an iterative algorithm. The iterations end when the
        /// <paramref name="maxNumberOfIterations"/> were performed, or when the
        /// <paramref name="tolerance"/> criterion is met - whichever comes first.
        /// </para>
        /// </remarks>
        public float GetParameterFromLength(float length, int maxNumberOfIterations, float tolerance)
        {
            if (tolerance <= 0)
            {
                throw new ArgumentOutOfRangeException("tolerance", "The tolerance must be greater than zero.");
            }

            int numberOfKeys = Count;

            if (numberOfKeys == 0)
            {
                return(float.NaN);
            }

            // Handle CurveLoopType.Linear:
            float curveStart  = Items[0].Parameter;
            float curveEnd    = Items[numberOfKeys - 1].Parameter;
            float curveLength = curveEnd - curveStart;

            if (length < curveStart && PreLoop == CurveLoopType.Linear)
            {
                var tangent = GetTangent(curveStart);
                return(curveStart - (curveStart - length) / tangent.Length);
            }

            if (length > curveEnd && PostLoop == CurveLoopType.Linear)
            {
                var tangent = GetTangent(curveEnd);
                return(curveEnd + (length - curveEnd) / tangent.Length);
            }

            if (Numeric.IsZero(curveLength))
            {
                return(curveStart);
            }

            // Correct parameter.
            float loopedLength = LoopParameter(length);

            // Find key index for the parameter.
            int index = GetKeyIndex(loopedLength);

            if (index == numberOfKeys - 1)
            {
                index--; // For the last key we take the previous spline.
            }
            // Get spline.
            var spline = GetSpline(index);

            // Get relative length on the segment from length on whole curve.
            float splineStart  = Items[index].Parameter;
            float splineEnd    = Items[index + 1].Parameter;
            float splineLength = (splineEnd - splineStart);

            loopedLength = loopedLength - splineStart;
            Debug.Assert(0 <= loopedLength && loopedLength <= splineLength);

            float result = CurveHelper.GetParameter(spline, loopedLength, splineLength, maxNumberOfIterations, tolerance);

            float localParameter = Items[index].Parameter + result * splineLength;

            ((IRecyclable)spline).Recycle();
            spline = null;

            // Handle looping: We return a parameter that is outside if the original length parameter is outside.
            // Otherwise the returned parameter would correspond to the correct parameter on the path, but
            // the total distance from the first key would wrong because some "loops" are missing.
            if (length < curveStart && PreLoop != CurveLoopType.Constant)
            {
                int numberOfPeriods = (int)((length - curveEnd) / curveLength);
                if (PreLoop == CurveLoopType.Oscillate && numberOfPeriods % 2 == -1)
                {
                    return(curveStart + curveStart - localParameter + curveLength * (numberOfPeriods + 1)); // odd = mirrored
                }
                else
                {
                    return(localParameter + numberOfPeriods * curveLength);
                }
            }
            else if (length > curveEnd && PostLoop != CurveLoopType.Constant)
            {
                int numberOfPeriods = (int)((length - curveStart) / curveLength);
                if (PostLoop == CurveLoopType.Oscillate && numberOfPeriods % 2 == 1)
                {
                    return(curveEnd + curveEnd - localParameter + curveLength * (numberOfPeriods - 1)); // odd = mirrored
                }
                else
                {
                    return(localParameter + numberOfPeriods * curveLength);
                }
            }
            else
            {
                return(localParameter);
            }
        }
Ejemplo n.º 7
0
        protected override void OnUpdateLines(int startIndex, int endIndexExclusive, double[] xPositions, double[] basePositions, double[] yPositions)
        {
            if (Data.Count <= 1)
            {
                return;
            }

            bool reversed = XAxis.Scale.Reversed;
            bool horizontalStepLineVisible = HorizontalStepLineVisible;
            bool verticalStepLineVisible   = VerticalStepLineVisible;
            bool filled        = Filled;
            var  interpolation = EffectiveInterpolation;

            int numberOfDataPoints = Data.Count;

            // Lines are drawn from index i to i+1.
            startIndex = Math.Max(0, startIndex - 1);

            // For centered steps one additional data point needs to be rendered.
            if (interpolation == ChartInterpolation.CenteredSteps)
            {
                endIndexExclusive = Math.Min(numberOfDataPoints, endIndexExclusive + 1);
            }

            for (int i = startIndex; i < endIndexExclusive; i++)
            {
                if (Numeric.IsNaN(xPositions[i]) || Numeric.IsNaN(yPositions[i]))
                {
                    continue;
                }

                Point previousPoint; //, previousPointBase;
                Point point, pointBase;
                Point nextPoint, nextPointBase;

                if (i - 1 >= 0)
                {
                    previousPoint = new Point(xPositions[i - 1], yPositions[i - 1]);
                    //previousPointBase = new Point(xPositions[i - 1], basePositions[i - 1]);
                }
                else
                {
                    previousPoint = new Point(double.NaN, double.NaN);
                    //previousPointBase = new Point(double.NaN, double.NaN);
                }

                point     = new Point(xPositions[i], yPositions[i]);
                pointBase = new Point(xPositions[i], basePositions[i]);

                if (i + 1 < numberOfDataPoints)
                {
                    nextPoint     = new Point(xPositions[i + 1], yPositions[i + 1]);
                    nextPointBase = new Point(xPositions[i + 1], basePositions[i + 1]);
                }
                else
                {
                    nextPoint     = new Point(double.NaN, double.NaN);
                    nextPointBase = new Point(double.NaN, double.NaN);
                }

                var lineFigures = new PathFigureCollection();
                var areaFigures = new PathFigureCollection();

                // Draw lines and area from i to i+1.
                if (interpolation == ChartInterpolation.Linear)
                {
                    // Linear interpolation
                    if (!Numeric.IsNaN(nextPoint.X) && !Numeric.IsNaN(nextPoint.Y))
                    {
                        var lineFigure = new PathFigure {
                            StartPoint = point
                        };
                        lineFigure.Segments.Add(new LineSegment {
                            Point = nextPoint
                        });
                        lineFigures.Add(lineFigure);

                        if (filled && !Numeric.IsNaN(pointBase.Y) && !Numeric.IsNaN(nextPointBase.Y))
                        {
                            var areaFigure = new PathFigure {
                                StartPoint = point
                            };
                            areaFigure.Segments.Add(new LineSegment {
                                Point = nextPoint
                            });
                            areaFigure.Segments.Add(new LineSegment {
                                Point = nextPointBase
                            });
                            areaFigure.Segments.Add(new LineSegment {
                                Point = pointBase
                            });
                            areaFigures.Add(areaFigure);
                        }
                    }
                }
                else if (interpolation == ChartInterpolation.CenteredSteps)
                {
                    // Centered steps
                    double centerBefore, centerAfter;
                    GetCenteredStep(previousPoint, point, nextPoint, out centerBefore, out centerAfter);

                    if (horizontalStepLineVisible)
                    {
                        var lineFigure = new PathFigure {
                            StartPoint = new Point(centerBefore, point.Y)
                        };
                        lineFigure.Segments.Add(new LineSegment {
                            Point = new Point(centerAfter, point.Y)
                        });
                        lineFigures.Add(lineFigure);
                    }

                    if (verticalStepLineVisible && !Numeric.IsNaN(nextPoint.X) && !Numeric.IsNaN(nextPoint.Y))
                    {
                        var lineFigure = new PathFigure {
                            StartPoint = new Point(centerAfter, point.Y)
                        };
                        lineFigure.Segments.Add(new LineSegment {
                            Point = new Point(centerAfter, nextPoint.Y)
                        });
                        lineFigures.Add(lineFigure);
                    }

                    if (filled && !Numeric.IsNaN(pointBase.Y))
                    {
                        var areaFigure = new PathFigure {
                            StartPoint = new Point(centerBefore, point.Y)
                        };
                        areaFigure.Segments.Add(new LineSegment {
                            Point = new Point(centerAfter, point.Y)
                        });
                        areaFigure.Segments.Add(new LineSegment {
                            Point = new Point(centerAfter, pointBase.Y)
                        });
                        areaFigure.Segments.Add(new LineSegment {
                            Point = new Point(centerBefore, pointBase.Y)
                        });
                        areaFigures.Add(areaFigure);
                    }
                }
                else if (interpolation == ChartInterpolation.LeftSteps && !reversed ||
                         interpolation == ChartInterpolation.RightSteps && reversed)
                {
                    // LeftSteps or Reversed RightSteps
                    if (!Numeric.IsNaN(nextPoint.X) && !Numeric.IsNaN(nextPoint.Y))
                    {
                        if (verticalStepLineVisible)
                        {
                            var lineFigure = new PathFigure {
                                StartPoint = point
                            };
                            lineFigure.Segments.Add(new LineSegment {
                                Point = new Point(point.X, nextPoint.Y)
                            });
                            lineFigures.Add(lineFigure);
                        }

                        if (horizontalStepLineVisible)
                        {
                            var lineFigure = new PathFigure {
                                StartPoint = new Point(point.X, nextPoint.Y)
                            };
                            lineFigure.Segments.Add(new LineSegment {
                                Point = nextPoint
                            });
                            lineFigures.Add(lineFigure);
                        }

                        if (filled && !Numeric.IsNaN(nextPointBase.Y))
                        {
                            var areaFigure = new PathFigure {
                                StartPoint = new Point(point.X, nextPoint.Y)
                            };
                            areaFigure.Segments.Add(new LineSegment {
                                Point = nextPoint
                            });
                            areaFigure.Segments.Add(new LineSegment {
                                Point = nextPointBase
                            });
                            areaFigure.Segments.Add(new LineSegment {
                                Point = new Point(point.X, nextPointBase.Y)
                            });
                            areaFigures.Add(areaFigure);
                        }
                    }
                }
                else
                {
                    // RightSteps or Reversed LeftSteps
                    if (!Numeric.IsNaN(nextPoint.X) && !Numeric.IsNaN(nextPoint.Y))
                    {
                        if (horizontalStepLineVisible)
                        {
                            var lineFigure = new PathFigure {
                                StartPoint = point
                            };
                            lineFigure.Segments.Add(new LineSegment {
                                Point = new Point(nextPoint.X, point.Y)
                            });
                            lineFigures.Add(lineFigure);
                        }

                        if (verticalStepLineVisible)
                        {
                            var lineFigure = new PathFigure {
                                StartPoint = new Point(nextPoint.X, point.Y)
                            };
                            lineFigure.Segments.Add(new LineSegment {
                                Point = nextPoint
                            });
                            lineFigures.Add(lineFigure);
                        }

                        if (filled && !Numeric.IsNaN(pointBase.Y) && !Numeric.IsNaN(nextPointBase.Y))
                        {
                            var areaFigure = new PathFigure {
                                StartPoint = point
                            };
                            areaFigure.Segments.Add(new LineSegment {
                                Point = new Point(nextPoint.X, point.Y)
                            });
                            areaFigure.Segments.Add(new LineSegment {
                                Point = new Point(nextPointBase.X, pointBase.Y)
                            });
                            areaFigure.Segments.Add(new LineSegment {
                                Point = pointBase
                            });
                            areaFigures.Add(areaFigure);
                        }
                    }
                }
                AddSegment(i, lineFigures, areaFigures);
            }

            Canvas.InvalidateMeasure();
        }
Ejemplo n.º 8
0
        protected override void OnKH()
        {
            switch (step)
            {
            case 1:
                encType = resultEncType;
                if (!ReferenceEquals(code, null))
                {
                    Numeric ka = program.GetValue(code.operand1);
                    key    = new NumericArray(ka);
                    length = Config.NumericBits;
                    if (key[0].GetEncType() == EncryptionType.None)
                    {
                        encType = EncryptionType.None;
                        if (key[0].GetEncType() == EncryptionType.None)
                        {
                            encType = EncryptionType.None;
                            if (key[0].GetUnsignedBigInteger() == 0)
                            {
                                keyH = new NumericArray(new Numeric(1, 0));
                            }
                            else
                            {
                                keyH = new NumericArray(new Numeric(0, 0));
                            }
                            // jump to round 3
                            step = 2;
                            Run();
                            break;
                        }
                    }
                }
                parallelism = key.Length;
                //Console.WriteLine("KH: " + key[0]);
                new HammingDistanceOnKH(party, line, this, key, keyH, length).Run();
                break;

            case 2:
                new FastEqualZeroOnKH(party, line, this, keyH, keyH, (int)Math.Ceiling(Math.Log(length + 1, 2))).Run();
                break;

            case 3:
                SetResult(encType, keyH.GetArray());
                break;

            case 4:
                InvokeCaller();
                break;

            default:
                throw new Exception();
                ////System.Diagnostics.Debug.Assert(le >= 2 || le == 0);
                //if (le > 2)
                //{
                //    le = (int)Math.Ceiling(Math.Log(le + 1, 2));
                //    new HammingDistanceOnKH(party, line, this, keyH, keyH, le).Run();
                //}
                //else if (le == 2)
                //{
                //    var OROperand = new Numeric[2 * parallelism];
                //    for (int p = 0; p < parallelism; ++p)
                //    {
                //        OROperand[2 * p] = keyH[p] >> 1;
                //        OROperand[2 * p + 1] = keyH[p].ModPow(1);
                //    }
                //    le = 0;
                //    new OROnKH(party, line, this, new NumericArray(OROperand), keyH).Run();
                //}
                //else
                //{
                //    Numeric[] kf = new Numeric[parallelism];
                //    for (int p = 0; p < parallelism; ++p)
                //    {
                //        kf[p] = keyH[p].ModPow(1);
                //        //kf[p].SetEncType(EncryptionType.XOR);
                //    }
                //    SetResult(kf);
                //}
                //break;
            }
        }
Ejemplo n.º 9
0
 public static void test_is_almost_zero()
 {
     Console.WriteLine("\nTesting is_almost_zero(Matrix A) ...\n");
     Numeric n = new Numeric();
     List<double[]> list3 = new List<double[]>() { new double[] { 4, 2, 1 }, new double[] { 2, 9, 3 }, new double[] { 1, 3, 16 } };
     Matrix A = Matrix.from_list(list3);
     Matrix L = n.Cholesky(A);
     Console.WriteLine("\n\tA: " + A.ToString());
     Console.WriteLine("\n\tExpect True: is_almost_zero(A - L*L.t) = " + n.is_almost_zero(A - L * L.Transpose()));
 }
Ejemplo n.º 10
0
 public NumericReply ReadNumReply(Numeric numeric)
 {
     // TODO: Implement ReadNumReply timeout
     while (ReadNumReply().Numeric != numeric) { }
     return last_reply;
 }
Ejemplo n.º 11
0
 public void NumericConstructorTest2()
 {
     NumericTypes type = new NumericTypes(); // TODO: Initialize to an appropriate value
     Numeric target = new Numeric(type);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Ejemplo n.º 12
0
        protected override void OnKH()
        {
            switch (step)
            {
            case 1:
                if (!ReferenceEquals(code, null))
                {
                    Numeric
                        k1 = program.GetValue(code.operand1),
                        k2 = program.GetValue(code.operand2);
                    TransformEncType(k1, k2);
                }
                else
                {
                    Run();
                }
                break;

            case 2:
                parallelism = key.Length / 2;
                kf          = new Numeric[parallelism];
                encType     = resultEncType;
                if (!ReferenceEquals(code, null))
                {
                    System.Diagnostics.Debug.Assert(parallelism == 1);
                    Numeric.Scale(key[0], key[1]);
                    if (key[0].GetEncType() == EncryptionType.None && key[1].GetEncType() == EncryptionType.None)
                    {
                        encType = EncryptionType.None;
                    }
                    // if at least one operand is not encrypted
                    if (key[0].GetEncType() == EncryptionType.None || key[1].GetEncType() == EncryptionType.None)
                    {
                        kf[0] = key[0] & key[1];
                        // jump to round 5
                        step = 4;
                        Run();
                        break;
                    }
                }
                scaleBits = new byte[parallelism];
                // byte[] k6 = fixedKey6;
                k6 = new Numeric[parallelism];
                ka = new Numeric[parallelism];
                Numeric[]
                kbAndEnck6ka = new Numeric[2 * parallelism],
                kb = new Numeric[parallelism];
                for (int p = 0; p < parallelism; ++p)
                {
                    ka[p] = key[2 * p];
                    kb[p] = key[2 * p + 1];
                    System.Diagnostics.Debug.Assert(ka[p].GetScaleBits() == kb[p].GetScaleBits());
                    scaleBits[p] = ka[p].GetScaleBits();
                    //ka[p].ResetScalingFactor();
                    //kb[p].ResetScalingFactor();
                    k6[p] = Utility.NextUnsignedNumeric(scaleBits[p]);
                    Numeric
                        enck6ka = ka[p] ^ k6[p];
                    kbAndEnck6ka[2 * p]     = kb[p];
                    kbAndEnck6ka[2 * p + 1] = enck6ka;
                }

                byte[] toEVH = Message.AssembleMessage(line, opType, false, k6);
                party.sender.SendTo(PartyType.EVH, toEVH);

                byte[] toHelper = Message.AssembleMessage(line, opType, false, kbAndEnck6ka);
                party.sender.SendTo(PartyType.Helper, toHelper);

                party.receiver.ReceiveFrom(PartyType.EVH, line, this, enckbXORk2b);
                break;

            case 3:
                party.receiver.ReceiveFrom(PartyType.Helper, line, this, enck5kbXORk2AndK7);
                break;

            case 4:
                for (int p = 0; p < parallelism; ++p)
                {
                    Numeric
                        enck5kbXORk2 = enck5kbXORk2AndK7[2 * p],
                        k7           = enck5kbXORk2AndK7[2 * p + 1],
                        t2           = ka[p] & enckbXORk2b[p],
                        t3           = k6[p] & enck5kbXORk2;
                    kf[p] = k7 ^ t2 ^ t3;
                    //kf[p].SetScalingFactor(scalingFactor[p]);
                }
                Run();
                break;

            case 5:
                SetResult(encType, kf);
                break;

            case 6:
                InvokeCaller();
                break;

            default:
                throw new Exception();
            }
        }
Ejemplo n.º 13
0
        protected override void OnEVH()
        {
            switch (step)
            {
            case 1:
                if (!ReferenceEquals(code, null))
                {
                    Numeric
                        enc_ka_a = program.GetValue(code.operand1),
                        enc_kb_b = program.GetValue(code.operand2);
                    TransformEncType(enc_ka_a, enc_kb_b);
                }
                else
                {
                    Run();
                }
                break;

            case 2:
                parallelism    = encVal.Length / 2;
                enc_kf_a_AND_b = new Numeric[parallelism];
                encType        = resultEncType;
                if (!ReferenceEquals(code, null))
                {
                    System.Diagnostics.Debug.Assert(parallelism == 1);
                    Numeric.Scale(encVal[0], encVal[1]);
                    // **tested**
                    // both operands are not encrypted
                    if (encVal[0].GetEncType() == EncryptionType.None && encVal[1].GetEncType() == EncryptionType.None)
                    {
                        encType = EncryptionType.None;
                    }
                    // if at least one operand is not encrypted
                    if (encVal[0].GetEncType() == EncryptionType.None || encVal[1].GetEncType() == EncryptionType.None)
                    {
                        enc_kf_a_AND_b[0] = encVal[0] & encVal[1];
                        // jump to round 5
                        step = 4;
                        Run();
                        break;
                    }
                }
                scaleBits   = new byte[parallelism];
                enckbxork2b = new Numeric[parallelism];
                enckaa      = new Numeric[parallelism];
                Numeric[]
                enckaaAndK2 = new Numeric[2 * parallelism],
                enckbb = new Numeric[parallelism];
                for (int p = 0; p < parallelism; ++p)
                {
                    enckaa[p] = encVal[2 * p];
                    enckbb[p] = encVal[2 * p + 1];
                    System.Diagnostics.Debug.Assert(enckaa[p].GetScaleBits() == enckbb[p].GetScaleBits());
                    scaleBits[p] = enckaa[p].GetScaleBits();
                    //enckaa[p].ResetScalingFactor();
                    //enckbb[p].ResetScalingFactor();

                    Numeric
                        k2 = Utility.NextUnsignedNumeric(scaleBits[p]);
                    enckbxork2b[p]         = enckbb[p] ^ k2;
                    enckaaAndK2[2 * p]     = enckaa[p];
                    enckaaAndK2[2 * p + 1] = k2;
                }

                byte[] toKH = Message.AssembleMessage(line, opType, false, enckbxork2b),
                toHelper = Message.AssembleMessage(line, opType, true, enckaaAndK2);
                party.sender.SendTo(PartyType.KH, toKH);
                party.sender.SendTo(PartyType.Helper, toHelper);
                party.receiver.ReceiveFrom(PartyType.KH, line, this, k6);
                break;

            case 3:
                party.receiver.ReceiveFrom(PartyType.Helper, line, this, enck7p7Andk5);
                break;

            case 4:
                for (int p = 0; p < parallelism; ++p)
                {
                    Numeric
                        t0      = enckaa[p] & enckbxork2b[p],
                        enck7p7 = enck7p7Andk5[2 * p],
                        k5      = enck7p7Andk5[2 * p + 1];
                    enc_kf_a_AND_b[p] = t0 ^ enck7p7 ^ (k5 & k6[p]);
                    //enckfab[p].SetScalingFactor(scalingFactor[p]);
                }
                Run();
                break;

            case 5:
                SetResult(encType, enc_kf_a_AND_b);
                break;

            case 6:
                InvokeCaller();
                break;

            default:
                throw new Exception();
            }
        }
            public void Add(Numeric.TimeDomain.Acoustic_Compact_FDTD.Node Node, int x, int y, int z, double dx, Rhino.Geometry.Point3d corner)
            {
                double dx3 = dx / 3;

                if (Node.GetType() == typeof(Numeric.TimeDomain.Acoustic_Compact_FDTD.Bound_Node))
                {
                    Point3d START = corner + new Rhino.Geometry.Point3d(dx * x, dx * y, dx * z);
                    DisplayMesh.Add(Mesh.CreateFromBox(new BoundingBox(START, START + new Point3d(dx, dx, dx)), 1, 1, 1));
                    List<Numeric.TimeDomain.Acoustic_Compact_FDTD.Bound_Node.Boundary> B = (Node as Numeric.TimeDomain.Acoustic_Compact_FDTD.Bound_Node_RDD).B_List;
                    Mesh[] corners = new Mesh[B.Count];

                    for (int i = 0; i < B.Count; i++)
                    {
                        switch (B[i])
                        {
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.AXNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(dx3, dx3, 0), START + new Point3d(2 * dx3, 2 * dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.AXPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(dx3, dx3, 2 * dx3), START + new Point3d(2 * dx3, 2 * dx3, 3 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.AYNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(dx3, 0, dx3), START + new Point3d(2 * dx3, dx3, 2 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.AYPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(dx3, 2 * dx3, dx3), START + new Point3d(2 * dx3, 3 * dx3, 2 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.AZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(0, dx3, dx3), START + new Point3d(dx3, 2 * dx3, 2 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.AZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, dx3, dx3), START + new Point3d(3 * dx3, 2 * dx3, 2 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.DXNegYNegZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START, START + new Point3d(dx3, dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.DXNegYNegZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(0, 0, 2 * dx3), START + new Point3d(dx3, dx3, 3 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.DXNegYPosZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(0, 2 * dx3, 0), START + new Point3d(dx3, 3 * dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.DXNegYPosZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(0, 2 * dx3, 2 * dx3), START + new Point3d(dx3, 3 * dx3, 3 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.DXPosYNegZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, 0, 0), START + new Point3d(3 * dx3, dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.DXPosYNegZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, 0, 2 * dx3), START + new Point3d(3 * dx3, dx3, 3 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.DXPosYPosZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, 2 * dx3, 0), START + new Point3d(3 * dx3, 3 * dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.DXPosYPosZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, 2 * dx3, 2 * dx3), START + new Point3d(3 * dx3, 3 * dx3, 3 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDXNegYNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(0, 0, dx3), START + new Point3d(dx3, dx3, 2 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDXNegYPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(0, 2 * dx3, 0), START + new Point3d(dx3, 3 * dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDXNegZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(0, dx3, 0), START + new Point3d(dx3, 2 * dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDXNegZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(0, dx3, 2 * dx3), START + new Point3d(dx3, 2 * dx3, 3 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDXPosYNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, 0, dx3), START + new Point3d(3 * dx3, dx3, 2 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDXPosYPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, 2 * dx3, dx3), START + new Point3d(3 * dx3, 3 * dx3, 2 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDXPosZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, dx3, 0), START + new Point3d(3 * dx3, 2 * dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDXPosZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(2 * dx3, dx3, 2 * dx3), START + new Point3d(3 * dx3, 2 * dx3, 3 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDYNegZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(dx3, 0, 0), START + new Point3d(2 * dx3, dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDYNegZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(dx3, 0, 2 * dx3), START + new Point3d(2 * dx3, dx3, 3 * dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDYPosZNeg:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(dx3, 2 * dx3, 0), START + new Point3d(2 * dx3, 3 * dx3, dx3)), 1, 1, 1);
                                break;
                            case Acoustic_Compact_FDTD.Bound_Node.Boundary.SDYPosZPos:
                                corners[i] = Mesh.CreateFromBox(new BoundingBox(START + new Point3d(dx3, 2 * dx3, 2 * dx3), START + new Point3d(2 * dx3, 3 * dx3, 3 * dx3)), 1, 1, 1);
                                break;
                        }

                        DirMesh.Add(corners);
                    }
                }

                this.Enabled = true;

            }
Ejemplo n.º 15
0
 public Message(string sender, Numeric command, params string[] argv)
     : this(sender, ((int)command).ToString("000"), argv)
 {
 }
 public void SendNumeric(Numeric numeric, params string[] argv)
 {
     var args = new List<string>();
     args.Add(username);
     args.AddRange(argv);
     SendFromServer(numeric, args.ToArray());
 }
 public void SendFromServer(Numeric numeric, params string[] argv)
 {
     Send(new Message(LOCALHOST, numeric, argv));
 }
 public void Send(string sender, Numeric numeric, params string[] argv)
 {
     Send(new Message(sender, numeric, argv));
 }
Ejemplo n.º 19
0
        /* Function:    solve_secant
         * Purpose:     Solves f(x) = 0 when function is differentiable by replacing f'(x)
         *              with difference quotient, using the current point and previous
         *              point visited in algorithm
         * Parameters:  x - Initial guess for solution x
         *              ap - absolute precision
         *              rp - relative precision
         *              ns - max number of iterations
         * Returns:     Approximation for exact solution.
         */
        public double solve_secant(double x, double ap = 0.000001, double rp = 0.0001, int ns = 20)
        {
            double fx = f(x);
            double Dfx = Df(x);

            double x_old = 0.0;
            double fx_old = 0.0;

            Numeric n = new Numeric();

            try
            {
                for (int k = 0; k < ns; k++)
                {
                    if (Math.Abs(Dfx) < ap)
                    {
                        throw new ArithmeticException("Unstable Solution");
                    }

                    x_old = x;
                    fx_old = fx;
                    x = x - fx / Dfx;

                    if ((k > 2) && (Math.Abs(x - x_old) < Math.Max(ap, Math.Abs(x) * rp)))
                    {
                        return x;
                    }

                    fx = f(x);
                    Dfx = (fx - fx_old) / (x - x_old);
                }

                throw new ArithmeticException("No convergence.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return Double.NaN;
        }
Ejemplo n.º 20
0
        public override void Render(IList <SceneNode> nodes, RenderContext context, RenderOrder order)
        {
            ThrowIfDisposed();

            if (nodes == null)
            {
                throw new ArgumentNullException("nodes");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            int numberOfNodes = nodes.Count;

            if (nodes.Count == 0)
            {
                return;
            }

            context.Validate(_effect);
            context.ThrowIfCameraMissing();

            var graphicsDevice   = context.GraphicsService.GraphicsDevice;
            var savedRenderState = new RenderStateSnapshot(graphicsDevice);

            graphicsDevice.RasterizerState   = RasterizerState.CullNone;
            graphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
            graphicsDevice.BlendState        = BlendState.AlphaBlend;

            // Camera properties
            var    cameraNode = context.CameraNode;
            Pose   cameraPose = cameraNode.PoseWorld;
            Matrix view       = (Matrix) new Matrix44F(cameraPose.Orientation.Transposed, new Vector3F(0));
            Matrix projection = cameraNode.Camera.Projection;

            _effectParameterViewProjection.SetValue(view * projection);

            // Update SceneNode.LastFrame for all visible nodes.
            int frame = context.Frame;

            cameraNode.LastFrame = frame;

            for (int i = 0; i < numberOfNodes; i++)
            {
                var node = nodes[i] as SkyObjectNode;
                if (node == null)
                {
                    continue;
                }

                // SkyObjectNode is visible in current frame.
                node.LastFrame = frame;

                // Get billboard axes from scene node pose.
                Matrix33F orientation = node.PoseWorld.Orientation;
                Vector3F  right       = orientation.GetColumn(0);
                Vector3F  up          = orientation.GetColumn(1);
                Vector3F  normal      = orientation.GetColumn(2);
                Vector3F  forward     = -normal;

                _effectParameterNormal.SetValue((Vector3)(normal));

                // ----- Render object texture.
                var texture = node.Texture;
                if (texture != null)
                {
                    _effectParameterUp.SetValue((Vector3)(up));
                    _effectParameterRight.SetValue((Vector3)(right));
                    _effectParameterSunLight.SetValue((Vector3)node.SunLight);
                    _effectParameterAmbientLight.SetValue(new Vector4((Vector3)node.AmbientLight, node.Alpha));
                    _effectParameterObjectTexture.SetValue(texture.TextureAtlas);
                    _effectParameterLightWrapSmoothness.SetValue(new Vector2(node.LightWrap, node.LightSmoothness));
                    _effectParameterSunDirection.SetValue((Vector3)node.SunDirection);

                    float halfWidthX = (float)Math.Tan(node.AngularDiameter.X / 2);
                    float halfWidthY = (float)Math.Tan(node.AngularDiameter.Y / 2);

                    // Texture coordinates of packed texture.
                    Vector2F texCoordLeftTop     = texture.GetTextureCoordinates(new Vector2F(0, 0), 0);
                    Vector2F texCoordRightBottom = texture.GetTextureCoordinates(new Vector2F(1, 1), 0);
                    float    texCoordLeft        = texCoordLeftTop.X;
                    float    texCoordTop         = texCoordLeftTop.Y;
                    float    texCoordRight       = texCoordRightBottom.X;
                    float    texCoordBottom      = texCoordRightBottom.Y;

                    _effectParameterTextureParameters.SetValue(new Vector4(
                                                                   (texCoordLeft + texCoordRight) / 2,
                                                                   (texCoordTop + texCoordBottom) / 2,
                                                                   1 / ((texCoordRight - texCoordLeft) / 2), // 1 / half extent
                                                                   1 / ((texCoordBottom - texCoordTop) / 2)));

                    _vertices[0].Position          = (Vector3)(forward - right * halfWidthX - up * halfWidthY);
                    _vertices[0].TextureCoordinate = new Vector2(texCoordLeft, texCoordBottom);
                    _vertices[1].Position          = (Vector3)(forward - right * halfWidthX + up * halfWidthY);
                    _vertices[1].TextureCoordinate = new Vector2(texCoordLeft, texCoordTop);
                    _vertices[2].Position          = (Vector3)(forward + right * halfWidthX - up * halfWidthY);
                    _vertices[2].TextureCoordinate = new Vector2(texCoordRight, texCoordBottom);
                    _vertices[3].Position          = (Vector3)(forward + right * halfWidthX + up * halfWidthY);
                    _vertices[3].TextureCoordinate = new Vector2(texCoordRight, texCoordTop);

                    if (context.IsHdrEnabled())
                    {
                        _effectPassObjectLinear.Apply();
                    }
                    else
                    {
                        _effectPassObjectGamma.Apply();
                    }

                    graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _vertices, 0, 2);
                }

                // ----- Render glows.
                if (node.GlowColor0.LengthSquared > 0 || node.GlowColor1.LengthSquared > 0)
                {
                    _effectParameterGlow0.SetValue(new Vector4((Vector3)node.GlowColor0, node.GlowExponent0));
                    _effectParameterGlow1.SetValue(new Vector4((Vector3)node.GlowColor1, node.GlowExponent1));

                    float halfWidth0 = (float)Math.Tan(Math.Acos(Math.Pow(node.GlowCutoffThreshold / node.GlowColor0.LargestComponent, 1 / node.GlowExponent0)));
                    if (!Numeric.IsPositiveFinite(halfWidth0))
                    {
                        halfWidth0 = 0;
                    }
                    float halfWidth1 = (float)Math.Tan(Math.Acos(Math.Pow(node.GlowCutoffThreshold / node.GlowColor1.LargestComponent, 1 / node.GlowExponent1)));
                    if (!Numeric.IsPositiveFinite(halfWidth1))
                    {
                        halfWidth1 = 0;
                    }
                    float halfWidth = Math.Max(halfWidth0, halfWidth1);

                    _vertices[0].Position          = (Vector3)(forward - right * halfWidth - up * halfWidth);
                    _vertices[0].TextureCoordinate = (Vector2) new Vector2F(0, 1);
                    _vertices[1].Position          = (Vector3)(forward - right * halfWidth + up * halfWidth);
                    _vertices[1].TextureCoordinate = (Vector2) new Vector2F(0, 0);
                    _vertices[2].Position          = (Vector3)(forward + right * halfWidth - up * halfWidth);
                    _vertices[2].TextureCoordinate = (Vector2) new Vector2F(1, 1);
                    _vertices[3].Position          = (Vector3)(forward + right * halfWidth + up * halfWidth);
                    _vertices[3].TextureCoordinate = (Vector2) new Vector2F(1, 0);

                    if (context.IsHdrEnabled())
                    {
                        _effectPassGlowLinear.Apply();
                    }
                    else
                    {
                        _effectPassGlowGamma.Apply();
                    }

                    graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _vertices, 0, 2);
                }
            }

            savedRenderState.Restore();
        }
Ejemplo n.º 21
0
        protected override double FindRoot(Func <double, double> function, double x0, double x1)
        {
            NumberOfIterations = 0;

            double yLow  = function(x0);
            double yHigh = function(x1);

            // Is one of the bounds the solution?
            if (Numeric.IsZero(yLow, EpsilonY))
            {
                return(x0);
            }
            if (Numeric.IsZero(yHigh, EpsilonY))
            {
                return(x1);
            }

            // Is the bracket valid?
            if (Numeric.AreEqual(x0, x1, EpsilonX) || yLow * yHigh >= 0)
            {
                return(double.NaN);
            }

            // Setup xLow and xHigh.
            double xLow, xHigh;

            if (yLow < 0)
            {
                xLow  = x0;
                xHigh = x1;
            }
            else
            {
                xLow  = x1;
                xHigh = x0;
                MathHelper.Swap(ref yLow, ref yHigh);
            }

            for (int i = 0; i < MaxNumberOfIterations; i++)
            {
                NumberOfIterations++;

                // The step size. dx steps from xLow to xHigh.
                double dx = xHigh - xLow;

                // Assume that the function is linear between xLow and xHigh.
                // And choose x for f(x) = 0 under this assumption
                double x = xLow + dx * yLow / (yLow - yHigh);
                double y = function(x);

                // Stop if x is the result or if the stepsize dx is less than Epsilon.
                if (Numeric.IsZero(y, EpsilonY) || Numeric.IsZero(dx, EpsilonX))
                {
                    return(x);
                }

                // Choose new bracket.
                if (y < 0)
                {
                    xLow = x;
                    yLow = y;
                }
                else
                {
                    xHigh = x;
                    yHigh = y;
                }
            }
            return(double.NaN);
        }
Ejemplo n.º 22
0
        protected override void OnKH()
        {
            switch (step)
            {
            case 1:
                if (!ReferenceEquals(code, null))
                {
                    Numeric
                        k1 = program.GetValue(code.operand1),
                        k2 = program.GetValue(code.operand2);
                    TransformEncType(k1, k2);
                }
                else
                {
                    Run();
                }
                break;

            case 2:
                parallelism = key.Length / 2;
                scaleBits   = new byte[parallelism];
                kf          = new Numeric[parallelism];
                encType     = resultEncType;
                if (!ReferenceEquals(code, null))
                {
                    scaleBits[0] = Numeric.Scale(key[0], key[1]);
                    // both not encrypted
                    if (key[0].GetEncType() == EncryptionType.None && key[1].GetEncType() == EncryptionType.None)
                    {
                        encType = EncryptionType.None;
                        if (scaleBits[0] == 0)
                        {
                            kf[0] = key[0] * key[1];
                            kf[0].SetScaleBits(0);
                        }
                        else
                        {
                            kf[0] = new Numeric((key[0].GetSignedBigInteger() * key[1].GetSignedBigInteger()) >> scaleBits[0], scaleBits[0]);
                        }
                        // jump to round 7
                        step = 6;
                        Run();
                        break;
                    }
                    // one is encrypted, the other is not
                    else if (key[0].GetEncType() == EncryptionType.None || key[1].GetEncType() == EncryptionType.None)
                    {
                        if (scaleBits[0] == 0)
                        {
                            kf[0] = key[0] * key[1];
                            kf[0].SetScaleBits(0);
                            // jump to round 7
                            step = 6;
                            Run();
                            break;
                        }
                        else
                        {
                            // if both operands are fixed-pointer integers,
                            // we treat the non-encryped operand as if the encrpted value is the original value and the key is 0,
                            // then we use the confidential protocol to computer the result.
                            if (key[0].GetEncType() == EncryptionType.None)
                            {
                                key[0] = new Numeric(0, scaleBits[0]);
                                //kf[0] = new Numeric(key[0].GetSignedBigInteger() * key[1].GetUnsignedBigInteger(), 0);
                            }
                            else
                            {
                                key[1] = new Numeric(0, scaleBits[0]);
                                //kf[0] = new Numeric(key[0].GetUnsignedBigInteger() * key[1].GetSignedBigInteger(), 0);
                            }
                            //krIdxMap.Add(0, 0);
                            //kr.Add(key[0]);
                            //// jump to round 5
                            //round = 4;
                            //Run();
                            //break;
                        }
                    }
                }

                k6 = new Numeric[parallelism];
                ka = new Numeric[parallelism];
                Numeric[]
                kbAndEnck6ka = new Numeric[2 * parallelism],
                kb = new Numeric[parallelism];
                for (int p = 0; p < parallelism; ++p)
                {
                    ka[p] = new Numeric(key[2 * p]);
                    kb[p] = new Numeric(key[2 * p + 1]);
                    System.Diagnostics.Debug.Assert(ka[p].GetScaleBits() == kb[p].GetScaleBits());
                    scaleBits[p] = ka[p].GetScaleBits();
                    ka[p].ResetScaleBits();
                    kb[p].ResetScaleBits();
                    k6[p] = Utility.NextUnsignedNumeric(0);
                    Numeric enck6ka = (new Numeric(0, 0) - ka[p]) + k6[p];
                    kbAndEnck6ka[2 * p]     = kb[p];
                    kbAndEnck6ka[2 * p + 1] = enck6ka;
                }

                var toEVH = Message.AssembleMessage(line, opType, false, k6);
                party.sender.SendTo(PartyType.EVH, toEVH);

                byte[] toHelper = Message.AssembleMessage(line, opType, false, kbAndEnck6ka);
                party.sender.SendTo(PartyType.Helper, toHelper);

                party.receiver.ReceiveFrom(PartyType.Helper, line, this, enck5kbplusk2AndK7);
                break;

            case 3:
                party.receiver.ReceiveFrom(PartyType.EVH, line, this, enckbplusk2b);
                break;

            case 4:
                int count = 0;
                for (int p = 0; p < parallelism; ++p)
                {
                    //System.Diagnostics.Debug.Assert(enck5kbplusk2AndK7[2 * p].GetScalingFactor() == scalingFactor[p]);
                    //System.Diagnostics.Debug.Assert(enck5kbplusk2AndK7[2 * p + 1].GetScalingFactor() == scalingFactor[p]);
                    //System.Diagnostics.Debug.Assert(enckbplusk2b[p].GetScalingFactor() == scalingFactor[p]);
                    Numeric
                        enck5kbplusk2 = enck5kbplusk2AndK7[2 * p],
                        k7            = enck5kbplusk2AndK7[2 * p + 1],
                        t2            = (new Numeric(0, 0) - ka[p]) * enckbplusk2b[p],
                        t3            = (new Numeric(0, 0) - k6[p]) * enck5kbplusk2;
                    kf[p] = k7 - t2 - t3;
                    if (scaleBits[p] != 0)
                    {
                        krIdxMap.Add(count++, p);
                        kr.Add(kf[p]);
                    }
                }
                Run();
                break;

            case 5:

                if (kr.Count != 0)
                {
                    newKey = new NumericArray();
                    new AddModToAddOnKH(party, line, this, new NumericArray(kr.ToArray()), newKey).Run();
                }
                else
                {
                    Run();
                }
                break;

            case 6:
                if (kr.Count != 0)
                {
                    for (int i = 0; i < kr.Count; ++i)
                    {
                        System.Diagnostics.Debug.Assert(newKey[i].GetUnsignedBigInteger() == newKey[i].GetSignedBigInteger());
                        kf[krIdxMap[i]] = new Numeric(newKey[i].GetUnsignedBigInteger() >> scaleBits[krIdxMap[i]], scaleBits[krIdxMap[i]]);
                        //kf[krIdxMap[i]] = new Numeric((BigInteger)(newKey[i].GetVal() / Math.Pow(2, scaleBits[krIdxMap[i]])), scaleBits[krIdxMap[i]]);
                        //kf[krIdxMap[i]].SetEncType(EncryptionType.AddMod);
                    }
                }
                Run();
                break;

            case 7:
                SetResult(encType, kf);
                break;

            case 8:
                InvokeCaller();
                break;

            default:
                throw new Exception();
            }
        }
Ejemplo n.º 23
0
 public void ToStringTest()
 {
     NumericTypes type = new NumericTypes(); // TODO: Initialize to an appropriate value
     Numeric target = new Numeric(type); // TODO: Initialize to an appropriate value
     string expected = string.Empty; // TODO: Initialize to an appropriate value
     string actual;
     actual = target.ToString();
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Ejemplo n.º 24
0
        protected override void OnEVH()
        {
            switch (step)
            {
            case 1:
                if (!ReferenceEquals(code, null))
                {
                    Numeric
                        enc_ka_a = program.GetValue(code.operand1),
                        enc_kb_b = program.GetValue(code.operand2);
                    TransformEncType(enc_ka_a, enc_kb_b);
                }
                else
                {
                    Run();
                }
                break;

            case 2:
                encType     = resultEncType;
                parallelism = encVal.Length / 2;
                enckfab     = new Numeric[parallelism];
                scaleBits   = new byte[parallelism];
                if (!ReferenceEquals(code, null))
                {
                    scaleBits[0] = Numeric.Scale(encVal[0], encVal[1]);
                    // both not encrypted
                    // **tested**
                    if (encVal[0].GetEncType() == EncryptionType.None && encVal[1].GetEncType() == EncryptionType.None)
                    {
                        encType = EncryptionType.None;
                        if (scaleBits[0] == 0)
                        {
                            enckfab[0] = encVal[0] * encVal[1];
                            enckfab[0].SetScaleBits(0);
                        }
                        else
                        {
                            enckfab[0] = new Numeric((encVal[0].GetSignedBigInteger() * encVal[1].GetSignedBigInteger()) >> scaleBits[0], scaleBits[0]);
                        }
                        // jump to round 7
                        step = 6;
                        Run();
                        break;
                    }
                    // one is encrypted, the other is not
                    else if (encVal[0].GetEncType() == EncryptionType.None || encVal[1].GetEncType() == EncryptionType.None)
                    {
                        // **tested**
                        if (scaleBits[0] == 0)
                        {
                            enckfab[0] = encVal[0] * encVal[1];
                            enckfab[0].SetScaleBits(0);
                            // jump to round 7
                            step = 6;
                            Run();
                            break;
                        }
                        // **tested**
                        else
                        {
                            // if both operands are fixed-pointer integers,
                            // we treat the non-encryped operand as if the encrpted value is the original value and the key is 0,
                            // then we use the confidential protocol to computer the result.


                            //if (encVal[0].GetEncType() == EncryptionType.None)
                            //{
                            //    enckfab[0] = new Numeric(encVal[0].GetSignedBigInteger() * encVal[1].GetUnsignedBigInteger(), 0);
                            //}
                            //else
                            //{
                            //    enckfab[0] = new Numeric(encVal[0].GetUnsignedBigInteger() * encVal[1].GetSignedBigInteger(), 0);
                            //}
                            //erIdxMap.Add(0, 0);
                            //er.Add(enckfab[0]);
                            //// jump to round 5
                            //round = 4;
                            //Run();
                            //break;
                        }
                    }
                }
                enckbplusk2b = new Numeric[parallelism];
                enckaa       = new Numeric[parallelism];
                Numeric[]
                enckaaAndK2 = new Numeric[2 * parallelism],
                enckbb = new Numeric[parallelism];
                for (int p = 0; p < parallelism; ++p)
                {
                    enckaa[p] = new Numeric(encVal[2 * p]);
                    enckbb[p] = new Numeric(encVal[2 * p + 1]);
                    System.Diagnostics.Debug.Assert(enckaa[p].GetScaleBits() == enckbb[p].GetScaleBits());
                    scaleBits[p] = enckaa[p].GetScaleBits();
                    enckaa[p].ResetScaleBits();
                    enckbb[p].ResetScaleBits();
                    // System.Diagnostics.Debug.Assert(encVal[2 * p + 1].GetScalingFactor() == scalingFactor[p]);
                    // byte[] k2 = fixedKey2;
                    Numeric
                        k2 = Utility.NextUnsignedNumeric(0);
                    enckbplusk2b[p]        = enckbb[p] + k2;
                    enckaaAndK2[2 * p]     = enckaa[p];
                    enckaaAndK2[2 * p + 1] = k2;
                }

                var toKH = Message.AssembleMessage(line, opType, false, enckbplusk2b);
                party.sender.SendTo(PartyType.KH, toKH);

                var toHelper = Message.AssembleMessage(line, opType, true, enckaaAndK2);
                party.sender.SendTo(PartyType.Helper, toHelper);
                party.receiver.ReceiveFrom(PartyType.KH, line, this, k6);
                break;

            case 3:
                party.receiver.ReceiveFrom(PartyType.Helper, line, this, enck7p7iAndK5);
                break;

            case 4:

                int count = 0;
                for (int p = 0; p < parallelism; ++p)
                {
                    //System.Diagnostics.Debug.Assert(k6[p].GetScalingFactor() == scalingFactor[p]);
                    //System.Diagnostics.Debug.Assert(enck7p7iAndK5[2 * p].GetScalingFactor() == scalingFactor[p]);
                    //System.Diagnostics.Debug.Assert(enck7p7iAndK5[2 * p + 1].GetScalingFactor() == scalingFactor[p]);
                    Numeric
                        t0      = enckaa[p] * enckbplusk2b[p],
                        enck7p7 = enck7p7iAndK5[2 * p],
                        k5      = enck7p7iAndK5[2 * p + 1];
                    enckfab[p] = t0 + enck7p7 + ((new Numeric(0, 0) - k5) * (new Numeric(0, 0) - k6[p]));
                    if (scaleBits[p] != 0)
                    {
                        erIdxMap.Add(count++, p);
                        //er.Add(new Numeric(enckfab[p].ToUnsignedBigInteger() & Numeric.oneMaskMap[scalingFactor[p]], 0));
                        er.Add(enckfab[p]);
                    }
                }
                Run();
                break;

            case 5:
                if (er.Count != 0)
                {
                    enc_newKey_a = new NumericArray();
                    new AddModToAddOnEVH(party, line, this, new NumericArray(er.ToArray()), enc_newKey_a).Run();
                }
                else
                {
                    Run();
                }
                break;

            case 6:
                if (er.Count != 0)
                {
                    for (int i = 0; i < er.Count; ++i)
                    {
                        //System.Diagnostics.Debug.WriteLine(enc_newKey_a[i].GetUnsignedBigInteger());
                        //System.Diagnostics.Debug.WriteLine(enc_newKey_a[i].GetSignedBigInteger());
                        System.Diagnostics.Debug.Assert(enc_newKey_a[i].GetUnsignedBigInteger() == enc_newKey_a[i].GetSignedBigInteger());
                        enckfab[erIdxMap[i]] = new Numeric(enc_newKey_a[i].GetUnsignedBigInteger() >> scaleBits[erIdxMap[i]], scaleBits[erIdxMap[i]]);
                        // enckfab[erIdxMap[i]] = new Numeric((BigInteger)(enc_paddedKey_a[i].GetVal() / Math.Pow(2, scaleBits[erIdxMap[i]])), scaleBits[erIdxMap[i]]);
                    }
                }
                Run();
                break;

            case 7:
                SetResult(encType, enckfab);
                break;

            case 8:
                InvokeCaller();
                break;

            default:
                throw new Exception();
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// returns the lengths of the number
        /// </summary>
        /// <param name="thisNumber"></param>
        /// <param name="wholeNumberLength"></param>
        /// <param name="decimalLength"></param>
        public static void GetNumericLengths(this INumeric thisNumber,
            out Numeric wholeNumberLength,
            out Numeric decimalLength)
        {
            if (thisNumber == null)
                throw new ArgumentNullException("thisNumber");

            var counter1 = thisNumber.GetCompatibleZero().HasAddition();
            var counter2 = thisNumber.GetCompatibleZero().HasAddition();
            thisNumber.ZoneIterate((node) =>
            {
                counter1.AddOne();
            }, (node) =>
            {
                counter2.AddOne();
            }, false);

            wholeNumberLength = counter1.InnermostNumeric;
            decimalLength = counter2.InnermostNumeric;
        }
Ejemplo n.º 26
0
        // -----------------------
        // ------ VALUE ----------
        // -----------------------

        public T Value(T x)
        {
            Numeric <T, C> xNew = x - x0;

            return(((a * xNew + b) * xNew + c) * xNew + d);
        }
Ejemplo n.º 27
0
        public static void test_condition_number()
        {
            Numeric n = new Numeric();
            List<double[]> list1 = new List<double[]>() { new double[] { 1, 2 }, new double[] { 3, 4 } };

            Console.WriteLine("\nTesting test_condition_number(Matrix A) ...\n");
            try
            {
                Console.WriteLine("\tExpecting:\tCondition number of Matrix [[1, 2], [3, 4]] = 21");
                Console.WriteLine("\t   Result:\tCondition number of Matrix " + Matrix.from_list(list1) + " = " + n.condition_number(Matrix.from_list(list1)));
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e.ToString());
            }

            Console.WriteLine("\nTesting test_condition_number(f, x=None, h=0.000001) ...\n");
            try
            {
                MyFunction3 fn = new MyFunction3();
                Console.WriteLine("\tExpecting:\tCondition number of function f(x) = (x * x) - (5.0 * x) = 0.75");
                Console.WriteLine("\t   Result:\tCondition number of function f(x) = (x * x) - (5.0 * x) = " + n.condition_number(fn, 1));
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e.ToString());
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// for a given list of numbers gets the longest lengths
        /// </summary>
        /// <param name="thisList"></param>
        /// <param name="wholeNumberLength"></param>
        /// <param name="decimalLength"></param>
        public static void GetNumericListLengths(this List<INumeric> thisList,
    out Numeric wholeNumberLength,
    out Numeric decimalLength)
        {
            if (thisList == null)
                throw new ArgumentNullException("thisList");

            Numeric maxWholeNumberLength = null;
            Numeric maxDecimalLength = null;

            thisList.WithEach(num =>
            {
                Numeric eachWholeNumberLength = null;
                Numeric eachDecimalLength = null;
                num.GetNumericLengths(out eachWholeNumberLength, out eachDecimalLength);

                if (eachWholeNumberLength.IsGreaterThan(maxWholeNumberLength))
                    maxWholeNumberLength = eachWholeNumberLength;

                if (eachDecimalLength.IsGreaterThan(maxDecimalLength))
                    maxDecimalLength = eachDecimalLength;

            });

            wholeNumberLength = maxWholeNumberLength;
            decimalLength = maxDecimalLength;
        }
Ejemplo n.º 29
0
 public static AddDigitOperationLine New(Numeric number1, Numeric number2, Numeric orderOfMagnitude)
 {
     return new AddDigitOperationLine(number1, number2, orderOfMagnitude);
 }
        // Add newAabb to the finalAabb list. If there is an overlap, the new AABB is clipped.
        // The final list will not have any overlaps.
        private void AddAabbWithClipping(List <Aabb> finalAabbs, ref Aabb newAabb)
        {
            // Add all new AABBs to stack.
            _aabbStack.Clear();
            _aabbStack.Push(newAabb);

            // Test all AABBs from the stack against the final AABBs. If an AABB passes all final AABB
            // overlap tests, it is added to final AABBs. If an AABB overlaps a final AABB, it is cut
            // into two parts. These two parts replace the AABB on the stack.
            int finalAabbsIndex = 0;

            while (_aabbStack.Count > 0)
            {
                // Get AABB from stack but do not remove it.
                var aabb = _aabbStack.Peek();

                if (finalAabbsIndex >= finalAabbs.Count)
                {
                    // AABB was checked against all final AABBs.
                    // Move from stack to final list.
                    _aabbStack.Pop();
                    finalAabbs.Add(aabb);
                    finalAabbsIndex = 0;
                    continue;
                }

                // Cut against finalAabbs[finalAabbsIndex].
                var finalAabb = finalAabbs[finalAabbsIndex];
                if (!HaveContactXZ(ref aabb, ref finalAabb))
                {
                    // No overlap. check against next AABB.
                    finalAabbsIndex++;
                    continue;
                }

                finalAabbsIndex = 0;

                // Overlap! Cut this AABB into two.
                // Remove from stack.
                _aabbStack.Pop();

                var aabbA = aabb;
                var aabbB = aabb;

                if (aabb.Minimum.X < finalAabb.Minimum.X)
                {
                    // Cut at final AABB min x:
                    aabbA.Maximum.X = finalAabb.Minimum.X;
                    aabbB.Minimum.X = finalAabb.Minimum.X;
                }
                else if (aabb.Maximum.X > finalAabb.Maximum.X)
                {
                    // Cut at final AABB max x:
                    aabbA.Maximum.X = finalAabb.Maximum.X;
                    aabbB.Minimum.X = finalAabb.Maximum.X;
                }
                else if (aabb.Minimum.Z < finalAabb.Minimum.Z)
                {
                    // Cut at final AABB min z:
                    aabbA.Maximum.Z = finalAabb.Minimum.Z;
                    aabbB.Minimum.Z = finalAabb.Minimum.Z;
                }
                else if (aabb.Maximum.Z > finalAabb.Maximum.Z)
                {
                    // Cut at final AABB max z:
                    aabbA.Maximum.Z = finalAabb.Maximum.Z;
                    aabbB.Minimum.Z = finalAabb.Maximum.Z;
                }
                else
                {
                    // AABB is totally inside and is not needed.

                    continue;
                }

                // Add non-empty AABBs to stack.
                if (!Numeric.AreEqual(aabbA.Minimum.X, aabbA.Maximum.X) &&
                    !Numeric.AreEqual(aabbA.Minimum.Z, aabbA.Maximum.Z))
                {
                    _aabbStack.Push(aabbA);
                }

                if (!Numeric.AreEqual(aabbB.Minimum.X, aabbB.Maximum.X) &&
                    !Numeric.AreEqual(aabbB.Minimum.Z, aabbB.Maximum.Z))
                {
                    _aabbStack.Push(aabbB);
                }
            }
        }
Ejemplo n.º 31
0
        protected override void OnEVH()
        {
            switch (step)
            {
            case 1:
                parallelism = encVal.Length;
                encType     = resultEncType;
                if (!ReferenceEquals(code, null))
                {
                    Numeric enckaa = program.GetValue(code.operand1);
                    encVal = new NumericArray(enckaa);
                    length = Config.NumericBits;
                    if (encVal[0].GetEncType() == EncryptionType.None)
                    {
                        encType = EncryptionType.None;
                        if (encVal[0].GetUnsignedBigInteger() == 0)
                        {
                            encH = new NumericArray(new Numeric(1, 0));
                        }
                        else
                        {
                            encH = new NumericArray(new Numeric(0, 0));
                        }
                        // jump to round 4
                        step = 3;
                        Run();
                        break;
                    }
                }
                new HammingDistanceOnEVH(party, line, this, encVal, encH, length).Run();
                break;

            case 2:
                new FastEqualZeroOnEVH(party, line, this, encH, encH, (int)Math.Ceiling(Math.Log(length + 1, 2))).Run();
                break;

            case 3:
                // as subfunction, the result should be 0 if secret == 0
                // however the result from FastEqualZero if 1 if secret == 0
                if (ReferenceEquals(code, null))
                {
                    for (int p = 0; p < parallelism; p++)
                    {
                        encH[p] ^= new Numeric(1, 0);
                    }
                }
                Run();
                break;

            case 4:
                SetResult(encType, encH.GetArray());
                break;

            case 5:
                InvokeCaller();
                break;

            default:
                throw new Exception();
                ////System.Diagnostics.Debug.Assert(le >= 2 || le == 0);
                //if (le > 2)
                //{
                //    le = (int)Math.Ceiling(Math.Log(le + 1, 2));
                //    new HammingDistanceOnEVH(party, line, this, encH, encH, le).Run();
                //}
                //else if (le == 2)
                //{
                //    var OROperand = new Numeric[2 * parallelism];
                //    for (int p = 0; p < parallelism; ++p)
                //    {
                //        OROperand[2 * p] = encH[p] >> 1;
                //        OROperand[2 * p + 1] = encH[p].ModPow(1);
                //    }
                //    le = 0;
                //    new OROnEVH(party, line, this, new NumericArray(OROperand), encH).Run();
                //}
                //else
                //{
                //    Numeric[] enckf = new Numeric[parallelism];
                //    for (int p = 0; p < parallelism; ++p)
                //    {
                //        enckf[p] = encH[p].ModPow(1);
                //        //enckf[p].SetEncType(EncryptionType.XOR);
                //    }
                //    if(!ReferenceEquals(code, null))
                //    {
                //        // not as a subfunction
                //        enckf[0] ^= new Numeric(1, 0);
                //    }
                //    SetResult(enckf);
                //}
                //break;
            }
        }
Ejemplo n.º 32
0
        protected override Size ArrangeOverride(Size finalSize)
        {
            // Ensure that all axes are up to date.
            foreach (Axis axis in _monitoredAxes)
            {
                axis.Update();
            }

            UIElementCollection children = Children;

            for (int i = 0; i < children.Count; ++i)
            {
                UIElement child = children[i];
                if (child == null)
                {
                    continue;
                }

                // Get the child or one of its descendants that needs to be positioned.
                DependencyObject elementThatRequiresArrange = GetElementThatRequiresArrange(child);
                if (elementThatRequiresArrange == null)
                {
                    // This child ignores the attached properties (X1, Y1, X2, Y2).
                    Rect childBounds = new Rect(new Point(), finalSize);

                    // Arrange element,
                    child.Arrange(childBounds);

                    // Clip to chart area.
                    if (GetClipToChartArea(child))
                    {
                        ClipElementToChartArea(child, childBounds);
                    }
                }
                else
                {
                    // Determine alignment.
                    HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left;
                    VerticalAlignment   verticalAlignment   = VerticalAlignment.Top;
                    if (elementThatRequiresArrange is FrameworkElement)
                    {
                        FrameworkElement frameworkElement = (FrameworkElement)elementThatRequiresArrange;
                        horizontalAlignment = frameworkElement.HorizontalAlignment;
                        verticalAlignment   = frameworkElement.VerticalAlignment;
                    }

                    // Get associated axes.
                    Axis xAxis = GetXAxis(elementThatRequiresArrange);
                    Axis yAxis = GetYAxis(elementThatRequiresArrange);

                    // Check whether we have to position the element relative to a point (X1, Y1)
                    // or inside a region (X1, Y1) - (X2, Y2).
                    // Convert positions given in data values to pixel positions.
                    double x1 = xAxis.GetPosition(GetX1(elementThatRequiresArrange));
                    double y1 = yAxis.GetPosition(GetY1(elementThatRequiresArrange));
                    double x2 = xAxis.GetPosition(GetX2(elementThatRequiresArrange));
                    double y2 = yAxis.GetPosition(GetY2(elementThatRequiresArrange));

                    bool isX1Valid = Numeric.IsFinite(x1);
                    bool isY1Valid = Numeric.IsFinite(y1);
                    bool isX2Valid = Numeric.IsFinite(x2);
                    bool isY2Valid = Numeric.IsFinite(y2);

                    double availableWidth  = Double.PositiveInfinity;
                    double availableHeight = Double.PositiveInfinity;

                    if (!isX1Valid && !isX2Valid)
                    {
                        // No coordinates set. Use 0 and 'left' alignment.
                        x1 = 0;
                        x2 = Double.NaN;
                        horizontalAlignment = HorizontalAlignment.Left;
                    }
                    else if (!isX1Valid)
                    {
                        // Only X2 set. Use X2 as position.
                        x1 = x2;
                        x2 = Double.NaN;
                    }
                    else if (isX2Valid)
                    {
                        // X1 and X2 are set.
                        int result = Numeric.Compare(x1, x2);
                        if (result < 0)
                        {
                            // X1 < X2: Horizontal region.
                            availableWidth = x2 - x1;
                        }
                        else if (result == 0)
                        {
                            // X1 == X2: Use only X1.
                            x2 = Double.NaN;
                        }
                        else
                        {
                            // X2 > X1: Horizontal region, but swapped.
                            ChartHelper.Swap(ref x1, ref x2);
                            availableWidth = x2 - x1;
                        }
                    }

                    if (!isY1Valid && !isY2Valid)
                    {
                        // No coordinates set. Use 0 and 'top' alignment.
                        y1 = 0;
                        y2 = Double.NaN;
                        verticalAlignment = VerticalAlignment.Top;
                    }
                    else if (!isY1Valid)
                    {
                        // Only Y2 set. Use Y2 as position.
                        y1 = y2;
                        y2 = Double.NaN;
                    }
                    else if (isY2Valid)
                    {
                        // Y1 and Y2 are set.
                        int result = Numeric.Compare(y1, y2);
                        if (result < 0)
                        {
                            // Y1 < Y2: Horizontal region.
                            availableHeight = y2 - y1;
                        }
                        else if (result == 0)
                        {
                            // Y1 == Y2: Use only Y1.
                            y2 = Double.NaN;
                        }
                        else
                        {
                            // Y2 > Y1: Horizontal region, but swapped.
                            ChartHelper.Swap(ref y1, ref y2);
                            availableHeight = y2 - y1;
                        }
                    }

                    // Get size of child.
                    double elementWidth  = child.DesiredSize.Width;
                    double elementHeight = child.DesiredSize.Height;

                    if (elementWidth == 0.0 && elementHeight == 0.0 && child is FrameworkElement)
                    {
                        // Fix for Silverlight.
                        FrameworkElement frameworkElement = (FrameworkElement)child;
                        elementWidth  = frameworkElement.ActualWidth;
                        elementHeight = frameworkElement.ActualHeight;
                    }

                    // Compute bounds of the child element.
                    Rect childBounds = new Rect();

                    // Position child horizontally.
                    if (Numeric.IsNaN(x2))
                    {
                        // Position child relative to point.
                        switch (horizontalAlignment)
                        {
                        case HorizontalAlignment.Left:
                        case HorizontalAlignment.Stretch:
                            childBounds.X     = x1;
                            childBounds.Width = elementWidth;
                            break;

                        case HorizontalAlignment.Center:
                            childBounds.X     = x1 - elementWidth / 2.0;
                            childBounds.Width = elementWidth;
                            break;

                        case HorizontalAlignment.Right:
                            childBounds.X     = x1 - elementWidth;
                            childBounds.Width = elementWidth;
                            break;
                        }
                    }
                    else
                    {
                        // Position child inside horizontal region.
                        switch (horizontalAlignment)
                        {
                        case HorizontalAlignment.Left:
                            childBounds.X     = x1;
                            childBounds.Width = elementWidth;
                            break;

                        case HorizontalAlignment.Center:
                            childBounds.X     = x1 + availableWidth / 2.0 - elementWidth / 2.0;
                            childBounds.Width = elementWidth;
                            break;

                        case HorizontalAlignment.Right:
                            childBounds.X     = x2 - elementWidth;
                            childBounds.Width = elementWidth;
                            break;

                        case HorizontalAlignment.Stretch:
                            childBounds.X     = x1;
                            childBounds.Width = availableWidth;
                            break;
                        }
                    }

                    // Position child vertically.
                    if (Numeric.IsNaN(y2))
                    {
                        // Position child relative to point.
                        switch (verticalAlignment)
                        {
                        case VerticalAlignment.Top:
                        case VerticalAlignment.Stretch:
                            childBounds.Y      = y1;
                            childBounds.Height = elementHeight;
                            break;

                        case VerticalAlignment.Center:
                            childBounds.Y      = y1 - elementHeight / 2.0;
                            childBounds.Height = elementHeight;
                            break;

                        case VerticalAlignment.Bottom:
                            childBounds.Y      = y1 - elementHeight;
                            childBounds.Height = elementHeight;
                            break;
                        }
                    }
                    else
                    {
                        // Position child inside vertical region.
                        switch (verticalAlignment)
                        {
                        case VerticalAlignment.Top:
                            childBounds.Y      = y1;
                            childBounds.Height = elementHeight;
                            break;

                        case VerticalAlignment.Center:
                            childBounds.Y      = y1 + availableHeight / 2.0 - elementHeight / 2.0;
                            childBounds.Height = elementHeight;
                            break;

                        case VerticalAlignment.Bottom:
                            childBounds.Y      = y2 - elementHeight;
                            childBounds.Height = elementHeight;
                            break;

                        case VerticalAlignment.Stretch:
                            childBounds.Y      = y1;
                            childBounds.Height = availableHeight;
                            break;
                        }
                    }

                    // Arrange element.
                    child.Arrange(childBounds);

                    // Clip to chart area.
                    if (elementThatRequiresArrange is UIElement && GetClipToChartArea(elementThatRequiresArrange))
                    {
                        UIElement element = (UIElement)elementThatRequiresArrange;
                        ClipElementToChartArea(element, childBounds);
                    }
                }
            }

            return(finalSize);
        }
Ejemplo n.º 33
0
        public static void RunTest()
        {
            Console.WriteLine("choose the test:");
            Console.WriteLine(" 1. nested while loop");
            Console.WriteLine(" 2. nested if-else statement");
            Console.WriteLine(" 3. while Loop in if-else statement");
            Console.WriteLine(" 4. if-else statement in while loop");

            int  whichTest     = Convert.ToInt32(Console.ReadLine());
            int  keyLen        = 64;
            int  numericBitLen = 40;
            byte scaleBits     = 21;

            Config.SetGlobalParameters(keyLen, numericBitLen, scaleBits, false);
            int attempts = 1;

            Random rnd       = new Random(1);
            int    corrCount = 0;

            for (int i = 0; i < attempts; i++)
            {
                //int x = (Math.Abs(rnd.Next()) % 10);
                double x = 6;
                //int x = 0;
                double  err  = 0;
                double  corr = 0;
                Numeric res  = null;
                switch (whichTest)
                {
                case 1:
                    corr = CorrNestedWhileTest(x);
                    res  = NestedWhileTest(x);
                    break;

                case 2:
                    corr = CorrNestedIfElseTest(x);
                    res  = NestedIfElseTest(x);
                    break;

                case 3:
                    corr = CorrWhileInIfElseTest(x);
                    res  = WhileInIfElseTest(x);
                    break;

                case 4:
                    corr = CorrIfElseInWhileTest(x);
                    res  = IfElseInWhileTest(x);
                    break;

                default:
                    throw new ArgumentException();
                }

                err = Math.Abs(res.GetVal() - corr);
                if (err < 0.1)
                {
                    corrCount++;
                }

                Console.WriteLine("x: " + x + ", corr: " + corr + ", computed: " + res.GetVal());
            }
            Console.WriteLine("accuracy: " + corrCount / attempts);
        }
Ejemplo n.º 34
0
        public AdditionStep(Numeric arg1, Numeric arg2)
        {
            this.Arg1 = arg1;
            this.Arg2 = arg2;
            this.CarryLine = arg1.GetCompatibleZero();

            //get the order of magnitudes
            List<INumeric> list = new List<INumeric>();
            if(arg1 != null)
                list.Add(arg1);

            if(arg2 != null)
                list.Add(arg2);

            list.g
        }
Ejemplo n.º 35
0
        protected override void AddNodeEx(SceneNode node, RenderContext context)
        {
            bool hasMaxDistance = Numeric.IsPositiveFinite(node.MaxDistance);
            var  lodGroupNode   = node as LodGroupNode;
            bool isLodGroupNode = (lodGroupNode != null);

            float distance = 0;

            if (hasMaxDistance || isLodGroupNode)
            {
                // ----- Calculate view-normalized distance.
                // The view-normalized distance is the distance between scene node and
                // camera node corrected by the camera field of view. This metric is used
                // for distance culling and LOD selection.
                var cameraNode = context.LodCameraNode;
                distance = GraphicsHelper.GetViewNormalizedDistance(node, cameraNode);

                // Apply LOD bias. (The LOD bias is a factor that can be used to increase
                // or decrease the viewing distance.)
                distance *= cameraNode.LodBias * context.LodBias;
            }

            // ----- Distance Culling: Check whether scene node is within MaxDistance.
            if (hasMaxDistance && distance >= node.MaxDistance)
            {
                return; // Ignore scene node.
            }
            // ----- Optional: Fade out scene node near MaxDistance to avoid popping.
            if (context.LodBlendingEnabled && node.SupportsInstanceAlpha())
            {
                float d     = node.MaxDistance - distance;
                float alpha = (d < context.LodHysteresis) ? d / context.LodHysteresis : 1;
                node.SetInstanceAlpha(alpha);
            }

            if (isLodGroupNode)
            {
                // ----- Evaluate LOD group.
                var lodSelection = lodGroupNode.SelectLod(context, distance);

                // ----- Optional: LOD Blending.
                if (lodSelection.Next != null &&
                    context.LodBlendingEnabled &&
                    lodSelection.Current.SupportsInstanceAlpha() &&
                    lodSelection.Next.SupportsInstanceAlpha())
                {
                    // The LOD group is currently transitioning between two LODs. Both LODs
                    // have an "InstanceAlpha" material parameter, i.e. we can create a
                    // smooth transition by blending between both LODs.
                    // --> Render both LODs using screen door transparency (stipple patterns).
                    // The current LOD (alpha = 1 - t) is faded out and the next LOD is faded
                    // in (alpha = t).
                    // The fade-in uses the regular stipple pattern and the fade-out needs to
                    // use the inverted stipple pattern. If the alpha value is negative the
                    // shader will use the inverted stipple pattern - see effect Material.fx.)
                    AddSubtree(lodSelection.Current, context);
                    lodSelection.Current.SetInstanceAlpha(-(1 - lodSelection.Transition));

                    AddSubtree(lodSelection.Next, context);
                    lodSelection.Next.SetInstanceAlpha(lodSelection.Transition);
                }
                else
                {
                    // No blending between two LODs. Just show current LOD.
                    if (lodSelection.Current.SupportsInstanceAlpha())
                    {
                        lodSelection.Current.SetInstanceAlpha(1);
                    }

                    AddSubtree(lodSelection.Current, context);
                }
            }
            else
            {
                // ----- Handle normal nodes.
                AddNode(node);
            }
        }
Ejemplo n.º 36
0
 public static AdditionStep New(Numeric arg1, Numeric arg2)
 {
     return new AdditionStep(arg1, arg2);
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Measures the child elements of a <see cref="ChartPanel"/> in anticipation of arranging
        /// them during the <see cref="ArrangeOverride(Size)"/> pass.
        /// </summary>
        /// <param name="availableSize">
        /// An upper limit <see cref="Size"/> that should not be exceeded.
        /// </param>
        /// <returns>
        /// A <see cref="Size"/> that represents the size that is required to arrange child content.
        /// </returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            // Ensure that all axes are up to date.
            foreach (Axis axis in _monitoredAxes)
            {
                axis.Update();
            }

            // Measure each child and calculate the bounds of child.
            UIElementCollection children = Children;

            for (int i = 0; i < children.Count; ++i)
            {
                // Get child element.
                UIElement child = children[i];
                if (child == null)
                {
                    continue;
                }

                // Get the child or one of its descendants that needs to be positioned.
                DependencyObject elementThatRequiresArrange = GetElementThatRequiresArrange(child);
                if (elementThatRequiresArrange == null)
                {
                    // This child ignores the attached properties (X1, Y1, X2, Y2).
                    child.Measure(availableSize);
                    continue;
                }

                // Get associated axes.
                Axis xAxis = GetXAxis(elementThatRequiresArrange);
                Axis yAxis = GetYAxis(elementThatRequiresArrange);

                // Check whether we have to position the element relative to a point (X1, Y1)
                // or inside a region (X1, Y1) - (X2, Y2).
                // Convert positions given in data values to pixel positions.
                double x1 = xAxis.GetPosition(GetX1(elementThatRequiresArrange));
                double y1 = yAxis.GetPosition(GetY1(elementThatRequiresArrange));
                double x2 = xAxis.GetPosition(GetX2(elementThatRequiresArrange));
                double y2 = yAxis.GetPosition(GetY2(elementThatRequiresArrange));

                double availableWidth  = Double.PositiveInfinity;
                double availableHeight = Double.PositiveInfinity;

                if (Numeric.IsFinite(x1) && Numeric.IsFinite(x2))
                {
                    // X1 and X2 are set.
                    double range = Math.Abs(x2 - x1);
                    if (!Numeric.IsZero(range))
                    {
                        availableWidth = range;
                    }
                }

                if (Numeric.IsFinite(y1) && Numeric.IsFinite(y2))
                {
                    // Y1 and Y2 are set.
                    double range = Math.Abs(y2 - y1);
                    if (!Numeric.IsZero(range))
                    {
                        availableHeight = range;
                    }
                }

                // Measure child and store its desired arrangement.
                Size elementConstraint = new Size(availableWidth, availableHeight);
                child.Measure(elementConstraint);
            }

            // Do not demand any size.
            // (The ChartPanel is similar to a canvas.)
            return(new Size());
        }
        protected override float FindRoot(Func <float, float> function, float x0, float x1)
        {
            Debug.Assert(function != null);
            Debug.Assert(Derivative != null);

            NumberOfIterations = 0;

            float yLow  = function(x0);
            float yHigh = function(x1);

            // Is one of the bounds the solution?
            if (Numeric.IsZero(yLow, EpsilonY))
            {
                return(x0);
            }

            if (Numeric.IsZero(yHigh, EpsilonY))
            {
                return(x1);
            }

            // Is the bracket valid?
            if (Numeric.AreEqual(x0, x1, EpsilonX) || yLow * yHigh >= 0)
            {
                return(float.NaN);
            }

            float xLow, xHigh;

            if (yLow < 0)
            {
                xLow  = x0;
                xHigh = x1;
            }
            else
            {
                xLow  = x1;
                xHigh = x0;
            }

            // Initial guess:
            float x = (x0 + x1) / 2;

            // The step size before the last.
            float dxOld = Math.Abs(x1 - x0);
            // The step size.
            float dx = dxOld;

            float y = function(x);

            // Stop if x is the result or if the step size dx is less than Epsilon.
            if (Numeric.IsZero(y, EpsilonY) || Numeric.IsZero(dx, EpsilonX))
            {
                return(x);
            }

            for (int i = 0; i < MaxNumberOfIterations; i++)
            {
                NumberOfIterations++;

                float dyOverDt = Derivative(x);

                // Choose new x.
                // Bisect if Newton would jump out of the brackets or step size would be too small.
                if ((((x - xHigh) * dyOverDt - y) * ((x - xLow) * dyOverDt - y) > 0) ||
                    (Math.Abs(2 * y) > Math.Abs(dxOld * dyOverDt)))
                {
                    // Bisect.
                    dxOld = dx;
                    dx    = (xHigh - xLow) / 2;
                    x     = xLow + dx;
                }
                else
                {
                    // Newton step.
                    dxOld = dx;
                    dx    = y / dyOverDt;
                    x    -= dx;
                }

                y = function(x);

                // Stop if x is the result or if the step size dx is less than Epsilon.
                if (Numeric.IsZero(y, EpsilonY) || Numeric.IsZero(dx, EpsilonX))
                {
                    return(x);
                }

                // Choose new bracket.
                if (y < 0)
                {
                    xLow = x;
                }
                else
                {
                    xHigh = x;
                }
            }
            return(float.NaN);
        }
Ejemplo n.º 39
0
 public void Length2()
 {
   Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
   v.Length = 0.5f;
   Assert.IsTrue(Numeric.AreEqual(0.5f, v.Length));
 }
Ejemplo n.º 40
0
        public void ComputeCollision()
        {
            RayBoxAlgorithm algo = new RayBoxAlgorithm(new CollisionDetection());

            CollisionObject ray = new CollisionObject(new GeometricObject
            {
                Shape = new RayShape(new Vector3F(0, 0, 0), new Vector3F(-1, 0, 0), 10),
                Pose  = new Pose(new Vector3F(0, 0, 0)),
            });

            CollisionObject box = new CollisionObject(new GeometricObject
            {
                Shape = new BoxShape(2, 4, 8),
            });

            ContactSet set;

            set = algo.GetClosestPoints(ray, box);
            Assert.AreEqual(true, algo.HaveContact(ray, box));
            Assert.AreEqual(true, algo.HaveContact(box, ray));
            Assert.AreEqual(0, set[0].PenetrationDepth);
            Assert.AreEqual(0, algo.GetContacts(box, ray)[0].PenetrationDepth);
            Assert.AreEqual(new Vector3F(), algo.GetContacts(box, ray)[0].Position);

            // Hit + x face.
            ((GeometricObject)box.GeometricObject).Pose = new Pose(new Vector3F(-1, 2, -4));
            ((GeometricObject)ray.GeometricObject).Pose = new Pose(new Vector3F(1, 0.5f, -2));
            set = algo.GetClosestPoints(ray, box);
            Assert.AreEqual(true, algo.HaveContact(ray, box));
            Assert.AreEqual(true, algo.HaveContact(box, ray));
            Assert.AreEqual(1, set[0].PenetrationDepth);
            Assert.AreEqual(1, algo.GetContacts(box, ray)[0].PenetrationDepth);
            Assert.AreEqual(-Vector3F.UnitX, algo.GetContacts(ray, box)[0].Normal);
            Assert.AreEqual(new Vector3F(0, 0.5f, -2), algo.GetContacts(box, ray)[0].Position);

            ((GeometricObject)ray.GeometricObject).Pose     = new Pose(new Vector3F(3, 2, -2));
            ((RayShape)ray.GeometricObject.Shape).Direction = new Vector3F(-1, 1, 0).Normalized;
            algo.UpdateContacts(set, 0);
            Assert.AreEqual(false, algo.HaveContact(ray, box));
            Assert.AreEqual(false, algo.HaveContact(box, ray));
            Assert.AreEqual(0, set.Count);
            Assert.IsTrue(Numeric.AreEqual(-(float)Math.Sqrt(0.5 * 0.5 + 0.5 * 0.5), algo.GetClosestPoints(ray, box)[0].PenetrationDepth));

            // Face is separating plane.
            ((GeometricObject)ray.GeometricObject).Pose     = new Pose(new Vector3F(3, 2, -2));
            ((RayShape)ray.GeometricObject.Shape).Direction = new Vector3F(0, 1, 0);
            algo.UpdateContacts(set, 0);
            Assert.AreEqual(false, algo.HaveContact(ray, box));
            Assert.AreEqual(false, algo.HaveContact(box, ray));
            Assert.AreEqual(0, set.Count);

            // Hit -x face.
            ((GeometricObject)ray.GeometricObject).Pose     = new Pose(new Vector3F(-5, -1, 0));
            ((RayShape)ray.GeometricObject.Shape).Direction = new Vector3F(1, 1, 0).Normalized;
            set = set.Swapped;
            algo.UpdateContacts(set, 0);
            Assert.AreEqual(true, algo.HaveContact(ray, box));
            Assert.AreEqual(true, algo.HaveContact(box, ray));
            Assert.IsTrue(Numeric.AreEqual((float)Math.Sqrt(3 * 3 + 3 * 3), set[0].PenetrationDepth));
            Assert.AreEqual(-Vector3F.UnitX, set[0].Normal);
        }
Ejemplo n.º 41
0
 public virtual void Visit(Numeric numeric)
 {
 }
Ejemplo n.º 42
0
        internal static bool HaveContact(Aabb aabb, Vector3F rayOrigin, Vector3F rayDirectionInverse, float rayLength, float epsilon)
        {
            // Note: If HaveContact is called several times for the same ray, we could return
            // tMin and tMax --> Parameter (ref float tMin and ref float tMax). Check tMin and tMax
            // against the first results.

            // The points on a ray are x = rayOrigin + t * rayDirection.
            // The points on a plane follow this equation: x . planeNormal = planeDistanceFromOrigin.
            // Substituting the x in the second equation, we can solve for t and get:
            // t = (planeDistanceFromOrigin - rayOrigin . planeNormal) / (rayDirection . planeNormal)
            //
            // For Aabbs the planeNormals are the unit vectors.
            // The planeDistances are the components of Aabb.Minimum and Maximum.

            // Compute tMin and tMax for all plane intersections. If a tMin is greater than a
            // tMax we can abort early. If tMin <= rayLength and tMax >= 0 we have a hit.

            float tMin = 0;
            float tMax = rayLength;

            {
                // tMinX
                float nearPlaneDistanceX = (rayDirectionInverse.X > 0) ? aabb.Minimum.X - epsilon : aabb.Maximum.X + epsilon;
                float tMinX = (nearPlaneDistanceX - rayOrigin.X) * rayDirectionInverse.X;
                if (tMinX > tMax)
                {
                    return(false);
                }
                if (tMinX > tMin)
                {
                    tMin = tMinX;
                }

                // tMaxX
                float farPlaneDistanceX = (rayDirectionInverse.X > 0) ? aabb.Maximum.X + epsilon : aabb.Minimum.X - epsilon;
                float tMaxX             = (farPlaneDistanceX - rayOrigin.X) * rayDirectionInverse.X;
                if (tMin > tMaxX)
                {
                    return(false);
                }
                if (tMaxX < tMax)
                {
                    tMax = tMaxX;
                }

                // Note: tMinX/tMaxX can be NaN if the ray origin is in the min or max X plane and the
                // ray is parallel to the plane. In this degenerate case we do not care about the
                // result, so no special treatment is needed.
                Debug.Assert(tMinX <= tMaxX || Numeric.IsNaN(tMinX) || Numeric.IsNaN(tMaxX));
            }

            {
                // tMaxY
                float farPlaneDistanceY = (rayDirectionInverse.Y > 0) ? aabb.Maximum.Y + epsilon: aabb.Minimum.Y - epsilon;
                float tMaxY             = (farPlaneDistanceY - rayOrigin.Y) * rayDirectionInverse.Y;
                if (tMin > tMaxY)
                {
                    return(false);
                }
                if (tMaxY < tMax)
                {
                    tMax = tMaxY;
                }

                // tMinY
                float nearPlaneDistanceY = (rayDirectionInverse.Y > 0) ? aabb.Minimum.Y - epsilon : aabb.Maximum.Y + epsilon;
                float tMinY = (nearPlaneDistanceY - rayOrigin.Y) * rayDirectionInverse.Y;
                if (tMinY > tMax)
                {
                    return(false);
                }
                if (tMinY > tMin)
                {
                    tMin = tMinY;
                }
            }

            {
                // tMinZ
                float nearPlaneDistanceZ = (rayDirectionInverse.Z > 0) ? aabb.Minimum.Z - epsilon: aabb.Maximum.Z + epsilon;
                float tMinZ = (nearPlaneDistanceZ - rayOrigin.Z) * rayDirectionInverse.Z;
                if (tMinZ > tMax)
                {
                    return(false);
                }
                if (tMinZ > tMin)
                {
                    tMin = tMinZ;
                }

                // tMaxZ
                float farPlaneDistanceZ = (rayDirectionInverse.Z > 0) ? aabb.Maximum.Z + epsilon : aabb.Minimum.Z - epsilon;
                float tMaxZ             = (farPlaneDistanceZ - rayOrigin.Z) * rayDirectionInverse.Z;
                if (tMin > tMaxZ)
                {
                    return(false);
                }
                if (tMaxZ < tMax)
                {
                    tMax = tMaxZ;
                }
            }

            Debug.Assert(tMin <= tMax + epsilon || tMax < 0 || tMin >= rayLength || Numeric.IsNaN(tMin) || Numeric.IsNaN(tMax));

            if (tMax < 0)
            {
                return(false);
            }
            if (tMin > rayLength)
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 43
0
        public override Vector2F GetTangent(float parameter)
        {
            int numberOfKeys = Count;

            if (numberOfKeys == 0)
            {
                return(new Vector2F());
            }

            CurveKey2F firstKey   = Items[0];
            CurveKey2F lastKey    = Items[numberOfKeys - 1];
            float      curveStart = firstKey.Parameter;
            float      curveEnd   = lastKey.Parameter;

            if (PreLoop == CurveLoopType.Constant && parameter < curveStart ||
                PostLoop == CurveLoopType.Constant && parameter > curveEnd)
            {
                return(Vector2F.UnitX);
            }

            // Correct parameter.
            float loopedParameter = LoopParameter(parameter);
            ICurve <float, float> xSpline, ySpline;

            // Note: Tangents from splines are relative to the spline parameter range [0,1]. We have
            // to divide by the spline length measured in the curve parameter unit.

            // Handle CurveLoopType.Linear:
            // If parameter is outside: Use spline tangent. Exceptions are Bézier and Hermite
            // were the exact tangent is given in the outer keys.
            if (loopedParameter < curveStart)
            {
                Debug.Assert(PreLoop == CurveLoopType.Linear);

                Vector2F tangent;
                switch (firstKey.Interpolation)
                {
                case SplineInterpolation.Bezier:
                    tangent = (firstKey.Point - firstKey.TangentIn) * 3;
                    break;

                case SplineInterpolation.Hermite:
                    tangent = firstKey.TangentIn;
                    break;

                case SplineInterpolation.StepLeft:
                case SplineInterpolation.StepCentered:
                case SplineInterpolation.StepRight:
                    tangent = Vector2F.UnitX;
                    break;

                default:
                    if (numberOfKeys > 1)
                    {
                        GetSplines(0, out xSpline, out ySpline);
                        tangent = new Vector2F(xSpline.GetTangent(0), ySpline.GetTangent(0));
                        ((IRecyclable)xSpline).Recycle();
                        ((IRecyclable)ySpline).Recycle();
                    }
                    else
                    {
                        tangent = Vector2F.UnitX;
                    }
                    break;
                }

                float splineLength = (numberOfKeys > 1) ? Items[1].Parameter - curveStart : 0;
                return((splineLength > 0) ? tangent / splineLength : tangent);
            }
            else if (loopedParameter > curveEnd)
            {
                Debug.Assert(PostLoop == CurveLoopType.Linear);

                Vector2F tangent;
                switch (lastKey.Interpolation)
                {
                case SplineInterpolation.Bezier:
                    tangent = (lastKey.TangentOut - lastKey.Point) * 3;
                    break;

                case SplineInterpolation.Hermite:
                    tangent = lastKey.TangentOut;
                    break;

                case SplineInterpolation.StepLeft:
                case SplineInterpolation.StepCentered:
                case SplineInterpolation.StepRight:
                    tangent = Vector2F.UnitX;
                    break;

                default:
                    if (numberOfKeys > 1)
                    {
                        GetSplines(numberOfKeys - 2, out xSpline, out ySpline);
                        tangent = new Vector2F(xSpline.GetTangent(1), ySpline.GetTangent(1));
                        ((IRecyclable)xSpline).Recycle();
                        ((IRecyclable)ySpline).Recycle();
                    }
                    else
                    {
                        tangent = Vector2F.UnitX;
                    }
                    break;
                }

                float splineLength = (numberOfKeys > 1) ? curveEnd - Items[numberOfKeys - 2].Parameter : 0;
                return((splineLength > 0) ? tangent / splineLength : tangent);
            }
            else
            {
                if (numberOfKeys == 1)
                {
                    // Degenerate curves with 1 key.
                    // Note: The following tangents are not scaled because we do not have enough information.
                    if (PostLoop == CurveLoopType.Linear)
                    {
                        // Pick outgoing tangent.
                        CurveKey2F p = firstKey;
                        if (p.Interpolation == SplineInterpolation.Bezier)
                        {
                            return((p.TangentOut - p.Point) * 3);
                        }

                        if (p.Interpolation == SplineInterpolation.Hermite)
                        {
                            return(p.TangentOut);
                        }
                    }
                    else if (PreLoop == CurveLoopType.Linear)
                    {
                        // Pick incoming tangent.
                        CurveKey2F p = firstKey;
                        if (p.Interpolation == SplineInterpolation.Bezier)
                        {
                            return((p.Point - p.TangentIn) * 3);
                        }

                        if (p.Interpolation == SplineInterpolation.Hermite)
                        {
                            return(p.TangentIn);
                        }
                    }

                    return(Vector2F.UnitX);
                }

                int index = GetKeyIndex(loopedParameter);
                if (index == numberOfKeys - 1)
                {
                    index--; // For the last key we take the previous spline.
                }
                Debug.Assert(0 <= index && index < numberOfKeys - 1);
                CurveKey2F p2 = Items[index];
                CurveKey2F p3 = Items[index + 1];

                // Special case: Step interpolation.
                if (p2.Interpolation == SplineInterpolation.StepLeft ||
                    p2.Interpolation == SplineInterpolation.StepCentered ||
                    p2.Interpolation == SplineInterpolation.StepRight)
                {
                    return(Vector2F.UnitX);
                }

                float splineStart  = p2.Parameter;
                float splineEnd    = p3.Parameter;
                float splineLength = splineEnd - splineStart;

                // Get splines for this segment.
                GetSplines(index, out xSpline, out ySpline);

                // Find correct parameter.
                float relativeParameter = 0;
                if (!Numeric.IsZero(splineLength))
                {
                    if (Items[index].Interpolation == SplineInterpolation.Bezier ||
                        Items[index].Interpolation == SplineInterpolation.BSpline ||
                        Items[index].Interpolation == SplineInterpolation.CatmullRom ||
                        Items[index].Interpolation == SplineInterpolation.Hermite)
                    {
                        // x spline is not linearly proportional. Need root finding.
                        relativeParameter = CurveHelper.GetParameter(xSpline, loopedParameter, 20);
                        if (Numeric.IsNaN(relativeParameter) && Items[index].Interpolation == SplineInterpolation.BSpline)
                        {
                            // Search neighbor splines. BSpline do not normally go exactly from p2 to p3.
                            // Try left neighbor spline first.
                            if (index - 1 >= 0 && Items[index - 1].Interpolation == SplineInterpolation.BSpline)
                            {
                                ((IRecyclable)xSpline).Recycle();
                                ((IRecyclable)ySpline).Recycle();
                                GetSplines(index - 1, out xSpline, out ySpline);
                                relativeParameter = CurveHelper.GetParameter(xSpline, loopedParameter, 20);
                            }

                            // If we didn't get a solution search the right neighbor.
                            if (Numeric.IsNaN(relativeParameter) && index + 1 < numberOfKeys - 1 &&
                                Items[index + 1].Interpolation == SplineInterpolation.BSpline)
                            {
                                ((IRecyclable)xSpline).Recycle();
                                ((IRecyclable)ySpline).Recycle();
                                GetSplines(index + 1, out xSpline, out ySpline);
                                relativeParameter = CurveHelper.GetParameter(xSpline, loopedParameter, 20);
                            }
                        }
                        Debug.Assert(
                            Items[index].Interpolation == SplineInterpolation.BSpline
                            || // BSplines do sometimes not include the boundary points, but for the rest we expect a solution.
                            Numeric.AreEqual(
                                xSpline.GetPoint(relativeParameter),
                                loopedParameter,
                                Math.Max(Math.Abs(splineLength) * Numeric.EpsilonF * 10, Numeric.EpsilonF)));
                    }
                    else
                    {
                        relativeParameter = (loopedParameter - splineStart) / splineLength;
                    }
                }

                float tangentX = xSpline.GetTangent(relativeParameter);
                float tangentY = ySpline.GetTangent(relativeParameter);
                if (IsInMirroredOscillation(parameter))
                {
                    tangentY = -tangentY; // Mirrored direction.
                }
                ((IRecyclable)xSpline).Recycle();
                ((IRecyclable)ySpline).Recycle();

                return(new Vector2F(tangentX, tangentY) / splineLength);
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Called when the simulation wants this force effect to apply forces to rigid bodies.
        /// </summary>
        protected override void OnApply()
        {
            RigidBody chassis        = Vehicle.Chassis;
            Pose      chassisPose    = chassis.Pose;
            float     mass           = chassis.MassFrame.Mass;
            Vector3   up             = chassisPose.ToWorldDirection(Vector3.UnitY);
            float     deltaTime      = Simulation.Settings.Timing.FixedTimeStep;
            int       numberOfWheels = Vehicle.Wheels.Count;

            for (int i = 0; i < numberOfWheels; i++)
            {
                var wheel = Vehicle.Wheels[i];

                // Update contact info.
                wheel.PreviousSuspensionLength = wheel.SuspensionLength;
                wheel.UpdateContactInfo();

                float normalDotUp = Vector3.Dot(wheel.GroundNormal, up);
                if (!wheel.HasGroundContact || Numeric.IsLessOrEqual(normalDotUp, 0))
                {
                    // -----  The simple case: The wheel is in the air.
                    // To keep it simple: The wheel continues spinning in the same direction.

                    // Damp angular velocity.
                    wheel.AngularVelocity *= 0.99f;

                    // Update rotation angle.
                    wheel.RotationAngle += wheel.AngularVelocity * deltaTime;

                    // TODO: Slow down or stop spin when braking.
                    // TODO: Reverse velocity when force reverses.
                    continue;
                }


                // ----- The wheel touches the ground.

                // ----- Suspension force
                float springForce = wheel.SuspensionStiffness
                                    * mass
                                    * (wheel.SuspensionRestLength - wheel.SuspensionLength)
                                    * normalDotUp;

                // The compression velocity:
                // (Note: Alternatively we could compute the  velocity from point velocities of chassis
                // and the hit body.)
                float compressionVelocity = (wheel.PreviousSuspensionLength - wheel.SuspensionLength) / deltaTime;
                float damping             = (compressionVelocity > 0) ? wheel.SuspensionCompressionDamping : wheel.SuspensionRelaxationDamping;
                float dampingForce        = damping * mass * compressionVelocity;

                // Force acting on chassis in up direction:
                float normalForce = MathHelper.Clamp(springForce + dampingForce, 0, wheel.MaxSuspensionForce);

                // If the suspension has reached the minimum length, we must add a large force
                // that stops any further compression.
                if (wheel.SuspensionLength <= wheel.MinSuspensionLength)
                {
                    // ComputeStopImpulse computes an impulse that stops any movement between the
                    // ground and the wheel in a given direction (up direction in this case).
                    float force = ComputeStopImpulse(wheel, up) / deltaTime; // force = impulse / dt

                    // force can be negative if the ground and the chassis are already separating.
                    // Only apply the force if is positive (= it pushes the chassis away from the ground).
                    if (force > 0)
                    {
                        normalForce += force;
                    }
                }

                AddForce(chassis, normalForce * up, wheel.GroundPosition);
                AddForce(wheel.TouchedBody, -normalForce * up, wheel.GroundPosition);

                // ----- Ground tangents
                Vector3 right         = chassisPose.ToWorldDirection(Matrix.CreateRotationY(wheel.SteeringAngle) * Vector3.UnitX);
                Vector3 groundForward = Vector3.Cross(wheel.GroundNormal, right).Normalized;
                Vector3 groundRight   = Vector3.Cross(groundForward, wheel.GroundNormal).Normalized;

                // ----- Side force
                float sideForce = ComputeStopImpulse(wheel, groundRight) / deltaTime; // force = impulse / dt
                // Assume that all wheels act together:
                sideForce /= numberOfWheels;

                // ----- Forward force
                float rollingFrictionForce;
                if (Math.Abs(wheel.MotorForce) > wheel.BrakeForce)
                {
                    // If the motor is driving the car, assume that the friction force has the same
                    // magnitude (100% friction, the whole motor force is delivered to the ground.)
                    rollingFrictionForce = wheel.MotorForce - wheel.BrakeForce;
                }
                else
                {
                    // The motor is off, or we are braking.
                    // Compute a friction force that would stop the car.
                    rollingFrictionForce = ComputeStopImpulse(wheel, groundForward) / deltaTime;

                    // Limit the friction force by the wheel.RollingFrictionForce (can be 0) or the
                    // the current brake force.
                    float brakeForce  = wheel.BrakeForce - Math.Abs(wheel.MotorForce);
                    float maxFriction = Math.Max(wheel.RollingFrictionForce, brakeForce);
                    rollingFrictionForce = MathHelper.Clamp(rollingFrictionForce, -maxFriction, maxFriction);
                }

                // The current side force and rolling friction force assume perfect friction. But the
                // friction force is limited by the normal force that presses onto the ground:
                //   MaxFrictionForce = µ * NormalForce
                float maxFrictionForce = wheel.Friction * normalForce;

                // Compute combined force parallel to ground surface.
                Vector3 tangentForce       = rollingFrictionForce * groundForward + sideForce * groundRight;
                float   tangentForceLength = tangentForce.Length;
                if (tangentForceLength > maxFrictionForce)
                {
                    // Not enough traction - that means, we are sliding!
                    var skidForce    = tangentForceLength - maxFrictionForce;
                    var skidVelocity = skidForce * deltaTime / mass;
                    wheel.SkidEnergy = maxFrictionForce * skidVelocity * deltaTime;

                    // The friction forces must be scaled.
                    float factor = maxFrictionForce / tangentForceLength;
                    rollingFrictionForce *= factor;
                    sideForce            *= factor;
                }
                else
                {
                    // The force is within the friction cone. No sliding.
                    wheel.SkidEnergy = 0;
                }

                // Apply rolling friction force. This drives the car.
                AddForce(chassis, rollingFrictionForce * groundForward, wheel.GroundPosition);
                AddForce(wheel.TouchedBody, -rollingFrictionForce * groundForward, wheel.GroundPosition);

                // Apply side friction force
                // If we apply the side force on the ground position, the car starts rolling (tilt) in
                // tight curves. If we apply the force on a higher position, rolling is reduced.
                Vector3 sideForcePosition = wheel.GroundPosition + wheel.RollReduction * (wheel.SuspensionLength + wheel.Radius) * up;
                AddForce(chassis, sideForce * groundRight, sideForcePosition);
                AddForce(wheel.TouchedBody, -sideForce * groundRight, sideForcePosition);

                // ----- Update AngularVelocity and Rotation.
                // We set the angular velocity, so that the wheel matches the moving underground.
                Vector3 relativeContactVelocity = chassis.GetVelocityOfWorldPoint(wheel.GroundPosition)
                                                  - wheel.TouchedBody.GetVelocityOfWorldPoint(wheel.GroundPosition);
                float forwardVelocity = Vector3.Dot(relativeContactVelocity, groundForward);
                wheel.AngularVelocity = forwardVelocity / wheel.Radius;
                wheel.RotationAngle  += wheel.AngularVelocity * deltaTime;

                // TODO: Use a more realistic AngularVelocity!
                // - Apply the skid energy to show sliding wheels.
                // - Set AngularVelocity to 0 when brakes are active - for more dramatic effect.
            }
        }
Ejemplo n.º 45
0
        public bool IsNumerc_IsValid(string propertyValue)
        {
            //Create Validator
            var validator = new Numeric<Contact>();
            RuleValidatorContext<Contact, string> context = BuildContextForLength(propertyValue);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return validator.Validate(context, null, notification);
        }
Ejemplo n.º 46
0
 public void registerNumeric <A>(
     string name, Ref <A> a, Numeric <A> num,
     ImmutableList <A> quickSetValues = null
     ) =>
 registerNumeric(name, a, num, num.fromInt(1), quickSetValues);
Ejemplo n.º 47
0
        internal static void GetMass(Shape shape, Vector3F scale, float densityOrMass, bool isDensity, float relativeDistanceThreshold, int iterationLimit,
                                     out float mass, out Vector3F centerOfMass, out Matrix33F inertia)
        {
            if (shape == null)
            {
                throw new ArgumentNullException("shape");
            }
            if (densityOrMass <= 0)
            {
                throw new ArgumentOutOfRangeException("densityOrMass", "The density or mass must be greater than 0.");
            }
            if (relativeDistanceThreshold < 0)
            {
                throw new ArgumentOutOfRangeException("relativeDistanceThreshold", "The relative distance threshold must not be negative.");
            }

            mass         = 0;
            centerOfMass = Vector3F.Zero;
            inertia      = Matrix33F.Zero;

            // Note: We support all shape types of DigitalRune Geometry.
            // To support user-defined shapes we could add an interface IMassSource which can be
            // implemented by shapes. In the else-case below we can check whether the shape implements
            // the interface.
            if (shape is EmptyShape)
            {
                return;
            }
            else if (shape is InfiniteShape)
            {
                mass    = float.PositiveInfinity;
                inertia = Matrix33F.CreateScale(float.PositiveInfinity);
            }
            else if (shape is BoxShape)
            {
                GetMass((BoxShape)shape, scale, densityOrMass, isDensity, out mass, out inertia);
            }
            else if (shape is CapsuleShape)
            {
                GetMass((CapsuleShape)shape, scale, densityOrMass, isDensity, out mass, out inertia);
            }
            else if (shape is ConeShape)
            {
                GetMass((ConeShape)shape, scale, densityOrMass, isDensity, out mass, out centerOfMass, out inertia);
            }
            else if (shape is CylinderShape)
            {
                GetMass((CylinderShape)shape, scale, densityOrMass, isDensity, out mass, out inertia);
            }
            else if (shape is ScaledConvexShape)
            {
                var scaledConvex = (ScaledConvexShape)shape;
                GetMass(scaledConvex.Shape, scale * scaledConvex.Scale, densityOrMass, isDensity, relativeDistanceThreshold, iterationLimit, out mass, out centerOfMass, out inertia);
            }
            else if (shape is SphereShape)
            {
                GetMass((SphereShape)shape, scale, densityOrMass, isDensity, out mass, out inertia);
            }
            else if (shape is TransformedShape)
            {
                var transformed = (TransformedShape)shape;

                // Call GetMass for the contained GeometricObject.
                GetMass(transformed.Child, scale, densityOrMass, isDensity, relativeDistanceThreshold, iterationLimit, out mass, out centerOfMass, out inertia);
            }
            else if (shape is HeightField)
            {
                // Height fields should always be static. Therefore, they we can treat them as having
                // infinite or zero mass.
                return;
            }
            else if (shape is CompositeShape)
            {
                var   composite = (CompositeShape)shape;
                float density   = (isDensity) ? densityOrMass : 1;
                foreach (var child in composite.Children)
                {
                    // Call GetMass for the child geometric object.
                    float     childMass;
                    Vector3F  childCenterOfMass;
                    Matrix33F childInertia;
                    GetMass(child, scale, density, true, relativeDistanceThreshold, iterationLimit, out childMass, out childCenterOfMass, out childInertia);

                    // Add child mass to total mass.
                    mass = mass + childMass;

                    // Add child inertia to total inertia and consider the translation.
                    inertia += GetTranslatedMassInertia(childMass, childInertia, childCenterOfMass);

                    // Add weighted centerOfMass.
                    centerOfMass = centerOfMass + childCenterOfMass * childMass;
                }

                // centerOfMass must be divided by total mass because child center of mass were weighted
                // with the child masses.
                centerOfMass /= mass;

                // Make inertia relative to center of mass.
                inertia = GetUntranslatedMassInertia(mass, inertia, centerOfMass);

                if (!isDensity)
                {
                    // Yet, we have not computed the correct total mass. We have to adjust the total mass to
                    // be equal to the given target mass.
                    AdjustMass(densityOrMass, ref mass, ref inertia);
                }
            }
            else if (iterationLimit <= 0)
            {
                // We do not have a special formula for this kind of shape and iteration limit is 0 or less.
                // --> Use mass properties of AABB.
                var aabb   = shape.GetAabb(scale, Pose.Identity);
                var extent = aabb.Extent;
                centerOfMass = aabb.Center;
                GetMass(extent, densityOrMass, isDensity, out mass, out inertia);
            }
            else
            {
                // We do not have a special formula for this kind of shape.
                // --> General polyhedron mass from triangle mesh.
                var mesh = shape.GetMesh(relativeDistanceThreshold, iterationLimit);
                mesh.Transform(Matrix44F.CreateScale(scale));
                GetMass(mesh, out mass, out centerOfMass, out inertia);

                // Mass was computed for density = 1. --> Scale mass.
                if (isDensity)
                {
                    var volume     = mesh.GetVolume();
                    var targetMass = volume * densityOrMass;
                    AdjustMass(targetMass, ref mass, ref inertia);
                }
                else
                {
                    AdjustMass(densityOrMass, ref mass, ref inertia);
                }

                if (Numeric.IsLessOrEqual(mass, 0))
                {
                    // If the mass is not valid, we fall back to the AABB mass.
                    // This can happen for non-closed meshes that have a "negative" volume.
                    GetMass(shape, scale, densityOrMass, isDensity, relativeDistanceThreshold, -1, out mass, out centerOfMass, out inertia);
                    return;
                }
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Raises the <see cref="ChartElement.Updated"/> event.
        /// </summary>
        /// <remarks>
        /// <strong>Notes to Inheritors:</strong> When overriding <see cref="OnUpdate"/> in a
        /// derived class, be sure to call the base class's <see cref="OnUpdate"/> method so that
        /// the base class <see cref="Chart"/> can update the data source if required.
        /// </remarks>
        protected override void OnUpdate()
        {
            base.OnUpdate(); // Updates the data source, if required.

            Debug.Assert(Canvas.Children.Count == 0, "Canvas should be cleared in base class.");

            if (Data == null || Data.Count == 0 || DataPointTemplate == null)
            {
                // A relevant property is not set.
                return;
            }

            Axis        xAxis       = XAxis;
            Axis        yAxis       = YAxis;
            Orientation orientation = EffectiveOrientation;
            Axis        baseAxis    = (orientation == Orientation.Vertical) ? xAxis : yAxis;

            // Number of bars in a cluster:
            int numberOfBarCharts = GetNumberOfBarCharts();

            // Index of this bar in the cluster:
            int currentClusterPosition = GetClusterPosition();

            double barWidth             = GetBarWidth();
            double effectiveBarGapWidth = EffectiveBarGapWidth;

            var  group       = Group as BarChartGroup;
            bool isClustered = (group != null && group.Grouping == BarChartGrouping.Clustered);

            // Prepare for clipping
            double leftCutoff  = baseAxis.Scale.Min;
            double rightCutoff = baseAxis.Scale.Max;

            int numberOfDataPoints = Data.Count;

            for (int i = 0; i < numberOfDataPoints; ++i)
            {
                // Check to see if any values are null. If so, then continue.
                double    barHeight;
                DataPoint data = GetPointWithGrouping(i, out barHeight);
                if (Numeric.IsNaN(data.X) || Numeric.IsNaN(data.Y))
                {
                    continue;
                }

                #region ----- Horizontal clipping of data values for speed-up -----
                {
                    // We cannot clip the current value because the value could be outside of the
                    // scale, but the bar could still be visible.
                    // Therefore we use the left and the right neighbor to check if the current
                    // value is too far off the scale.
                    if (i > 0)
                    {
                        double xPrevious = GetPointWithGrouping(i - 1).X;
                        double yPrevious = GetPointWithGrouping(i - 1).Y;
                        if (orientation == Orientation.Vertical && xPrevious > rightCutoff ||
                            orientation == Orientation.Horizontal && yPrevious > rightCutoff)
                        {
                            continue;
                        }
                    }

                    if (i < numberOfDataPoints - 1)
                    {
                        double xNext = GetPointWithGrouping(i + 1).X;
                        double yNext = GetPointWithGrouping(i + 1).Y;
                        if (orientation == Orientation.Vertical && xNext < leftCutoff ||
                            orientation == Orientation.Horizontal && yNext < leftCutoff)
                        {
                            continue;
                        }
                    }
                }
                #endregion

                double basePosition;      // Position on base axis.
                double dataPosition;      // Position on data axis
                double baseLinePosition;  // Get position of zero value base line on data axis.
                if (orientation == Orientation.Vertical)
                {
                    basePosition     = xAxis.GetPosition(data.X);
                    dataPosition     = yAxis.GetPosition(data.Y);
                    baseLinePosition = yAxis.GetPosition(data.Y - barHeight);
                }
                else
                {
                    basePosition     = yAxis.GetPosition(data.Y);
                    dataPosition     = xAxis.GetPosition(data.X);
                    baseLinePosition = xAxis.GetPosition(data.X - barHeight);
                }

                if (isClustered)
                {
                    // Clustered drawing of bars:
                    double leftBarPosition = basePosition - (((double)numberOfBarCharts) / 2 - 0.5f) * barWidth - ((double)numberOfBarCharts - 1) / 2 * barWidth * effectiveBarGapWidth;
                    basePosition = leftBarPosition + currentClusterPosition * (barWidth + barWidth * effectiveBarGapWidth);
                }

                // Get bar bounding rectangle.
                Point  upperLeftCorner = new Point();
                double width;
                double height;
                if (orientation == Orientation.Vertical)
                {
                    // Base is X.
                    upperLeftCorner.X = basePosition - barWidth / 2;
                    upperLeftCorner.Y = Math.Min(dataPosition, baseLinePosition);
                    width             = barWidth;
                    height            = Math.Abs(dataPosition - baseLinePosition);
                }
                else
                {
                    // Base is Y.
                    upperLeftCorner.X = Math.Min(dataPosition, baseLinePosition);
                    upperLeftCorner.Y = basePosition - barWidth / 2;
                    width             = Math.Abs(dataPosition - baseLinePosition);
                    height            = barWidth;
                }

                // Create the bar from the data template.
                var bar = CreateDataPoint(data.DataContext ?? data);
                if (bar == null)
                {
                    return;
                }

                Canvas.SetLeft(bar, upperLeftCorner.X);
                Canvas.SetTop(bar, upperLeftCorner.Y);
                bar.Width  = width;
                bar.Height = height;
                bar.Tag    = Data[i].Point;

                // Let derived classes change the appearance of the bar.
                OnPrepareBar(i, data, bar);

                Canvas.Children.Add(bar);
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        /// creates a number using a digit and an order of magnitude
        /// </summary>
        /// <param name="orderOfMag"></param>
        /// <param name="digit"></param>
        /// <returns></returns>
        public static IDigitNode GetDigitAtMagnitude(this INumeric thisNumber,
            Numeric orderOfMag)
        {
            if (thisNumber == null)
                throw new ArgumentNullException("thisNumber");

            if (orderOfMag == null)
                throw new ArgumentNullException("orderOfMag");

            if (orderOfMag.IsEqualTo(orderOfMag.GetCompatibleZero()))
                return thisNumber.ZerothDigit;

            IDigitNode rv = null;

            if (orderOfMag.IsPositive)
            {
                rv = thisNumber.ZerothDigit;
                orderOfMag.PerformThisManyTimes(x =>
                {
                    if (rv != null)
                        rv = rv.NextDigit();
                });
            }
            else
            {
                rv = thisNumber.ZerothDigit;
                orderOfMag.GetNegativeOf().PerformThisManyTimes(x =>
                {
                    if (rv != null)
                        rv = rv.PreviousDigit();
                });
            }

            return rv;
        }
Ejemplo n.º 50
0
        private List <DRMorphTargetContent> BuildMorphTargets(GeometryContent geometry, List <MeshContent> inputMorphTargets, int index)
        {
            int[] vertexReorderMap = _vertexReorderMaps[index];

            var morphTargets = new List <DRMorphTargetContent>();

            foreach (var inputMorphTarget in inputMorphTargets)
            {
                int numberOfVertices = geometry.Vertices.VertexCount;
                var morphGeometry    = inputMorphTarget.Geometry[index];

                // Copy relative positions and normals into vertex buffer.
                var       positions = morphGeometry.Vertices.Positions;
                var       normals   = morphGeometry.Vertices.Channels.Get <Vector3>(VertexChannelNames.Normal());
                Vector3[] data      = new Vector3[numberOfVertices * 2];
                for (int i = 0; i < numberOfVertices; i++)
                {
                    int originalIndex = vertexReorderMap[i];
                    data[2 * i]     = positions[originalIndex];
                    data[2 * i + 1] = normals[originalIndex];
                }

                // Determine if morph target is empty.
                bool isEmpty = true;
                for (int i = 0; i < data.Length; i++)
                {
                    // File formats and preprocessing can introduce some inaccuracies.
                    // --> Use a relative large epsilon. (The default Numeric.EpsilonF is too small.)
                    const float epsilon = 1e-4f;
                    if (!Numeric.IsZero(data[i].LengthSquared(), epsilon * epsilon))
                    {
                        Debug.Write(string.Format(
                                        CultureInfo.InvariantCulture,
                                        "Morph target \"{0}\", submesh index {1}: Position/normal delta is {2}.",
                                        inputMorphTarget.Name, index, data[i].Length()));

                        isEmpty = false;
                        break;
                    }
                }

                if (!isEmpty)
                {
                    // (Note: VertexStride is set explicitly in CreateMorphTargetVertexBuffer().)
                    // ReSharper disable once PossibleInvalidOperationException
                    int vertexOffset = _morphTargetVertexBuffer.VertexData.Length / _morphTargetVertexBuffer.VertexDeclaration.VertexStride.Value;
                    _morphTargetVertexBuffer.Write(
                        _morphTargetVertexBuffer.VertexData.Length,
                        12, // The size of one Vector3 in data is 12.
                        data);

                    morphTargets.Add(new DRMorphTargetContent
                    {
                        Name         = inputMorphTarget.Name,
                        VertexBuffer = _morphTargetVertexBuffer,
                        StartVertex  = vertexOffset,
                    });
                }
            }

            return((morphTargets.Count > 0) ? morphTargets : null);
        }
Ejemplo n.º 51
0
    public static void SetDigitAtMagnitude(this INumeric thisNumber,
 Numeric orderOfMag, string digit)
    {
        var dig = thisNumber.GetDigitAtMagnitude(orderOfMag);
        dig.SetValue(digit);
    }
Ejemplo n.º 52
0
        private void ComputeTicks_FirstPass(double axisLength, double minDistance, List <double> majorTicks, List <double> minorTicks)
        {
            // Determine distance between large ticks.
            bool   shouldCullMiddle;
            double majorTickStep = DetermineMajorTickStep(axisLength, minDistance, out shouldCullMiddle);

            if (majorTickStep < 0.0)
            {
                throw new ChartException("Internal error in LinearScale: Tick distance is negative.");
            }

            // Determine starting position.
            double first;

            if (!Numeric.IsNaN(MajorTickAnchor))
            {
                first = MajorTickAnchor + Math.Ceiling((Min - MajorTickAnchor) / majorTickStep) * majorTickStep;
            }
            else
            {
                if (Min > 0.0)
                {
                    double n = Math.Floor(Min / majorTickStep) + 1.0f;
                    first = n * majorTickStep;
                }
                else
                {
                    double n = Math.Floor(-Min / majorTickStep) - 1.0f;
                    first = -n * majorTickStep;
                }

                // The above calculation misses the first tick, if it is exactly at Min.
                if ((first - majorTickStep) >= Min)
                {
                    first -= majorTickStep;
                }
            }

            // Now make list of major tick positions.
            majorTicks.Clear();

            double position    = first;
            int    safetyCount = 0;

            while (position < Max && ++safetyCount < 5000)
            {
                majorTicks.Add(position);

                position += majorTickStep;

                // Clamp near zero-Values to zero, otherwise we could get a value like 5.553434e-17 instead of 0.
                if (Math.Abs(majorTickStep) > 1e-7 && Math.Abs(position) < 1e-7)  // Arbitrary epsilon value.
                {
                    position = 0;
                }
            }

            // The last value could be the Max limit + an epsilon. In this case we add a tick for the
            // Max value.
            if (Numeric.AreEqual(position, Max))
            {
                majorTicks.Add(Max);
            }

            // If the physical extent is too small, and the middle ticks should be turned into minor
            // ticks, then do this now.
            minorTicks.Clear();
            if (shouldCullMiddle)
            {
                if (majorTicks.Count > 2)
                {
                    for (int i = 1; i < majorTicks.Count - 1; ++i)
                    {
                        minorTicks.Add(majorTicks[i]);
                    }
                }

                var culledPositions = new List <double>
                {
                    majorTicks[0],
                    majorTicks[majorTicks.Count - 1]
                };
                majorTicks.Clear();

                foreach (double value in culledPositions)
                {
                    majorTicks.Add(value);
                }
            }
        }
Ejemplo n.º 53
0
 public static void test_cholesky()
 {
     Console.WriteLine("\nTesting Cholesky(Matrix A) ...\n");
     Numeric n = new Numeric();
     List<double[]> list3 = new List<double[]>() { new double[] { 4, 2, 1 }, new double[] { 2, 9, 3 }, new double[] { 1, 3, 16 } };
     Matrix A = Matrix.from_list(list3);
     Matrix L = n.Cholesky(A);
     Console.WriteLine("\n\tA: " + A.ToString());
     Console.WriteLine("\n\tExpect: Cholesky(A) = [[2.0, 0, 0], [1.0, 2.8284271247461903, 0], [0.5, 0.88388347648318433, 3.8689468851355402]]");
     Console.WriteLine("\t Result:Cholesky(A) = " + L.ToString());
 }
Ejemplo n.º 54
0
        private double DetermineMajorTickStep(double axisLength, double minDistance, out bool shouldCullMiddle)
        {
            shouldCullMiddle = false;

            // If the major tick has been explicitly set, then return this.
            if (!Numeric.IsNaN(MajorTickStep))
            {
                if (MajorTickStep <= 0.0f)
                {
                    throw new ChartException("MajorTickStep must be greater than zero.");
                }

                return(MajorTickStep);
            }

            // Otherwise we need to calculate the major tick step ourselves.

            // Adjust world max and min for offset and scale properties of axis.
            double range = Max - Min;

            // If axis has zero range, then return arbitrary number.
            if (Numeric.AreEqual(Min, Max))
            {
                return(1.0f);
            }

            double approxTickStep = minDistance / axisLength * range;
            double exponent       = Math.Floor(Math.Log10(approxTickStep));
            double mantissa       = Math.Pow(10.0, Math.Log10(approxTickStep) - exponent);

            // Determine next whole mantissa below the approx one.
            int mantissaIndex = Mantissas.Length - 1;

            for (int i = 1; i < Mantissas.Length; ++i)
            {
                if (mantissa < Mantissas[i])
                {
                    mantissaIndex = i - 1;
                    break;
                }
            }

            // Then choose next largest spacing.
            mantissaIndex += 1;
            if (mantissaIndex == Mantissas.Length)
            {
                mantissaIndex = 0;
                exponent     += 1.0;
            }

            // Now make sure that the returned value is such that at least two major tick marks will be
            // displayed.
            double tickStep     = Math.Pow(10.0, exponent) * Mantissas[mantissaIndex];
            double physicalStep = tickStep / range * axisLength;

            while (physicalStep > axisLength / 2)
            {
                shouldCullMiddle = true;

                mantissaIndex -= 1;
                if (mantissaIndex == -1)
                {
                    mantissaIndex = Mantissas.Length - 1;
                    exponent     -= 1.0;
                }

                tickStep     = Math.Pow(10.0, exponent) * Mantissas[mantissaIndex];
                physicalStep = tickStep / range * axisLength;
            }

            // And we're done.
            return(Math.Pow(10.0, exponent) * Mantissas[mantissaIndex]);
        }
Ejemplo n.º 55
0
        public static void test_is_almost_symmetric()
        {
            Console.WriteLine("\nTesting is_almost_symmetric() ...\n");
            Numeric n = new Numeric();

            Matrix A = Matrix.from_list(new List<double[]>() { new double[] { 1, 7, 3 }, new double[] { 7, 4, -5 }, new double[] { 3, -5, 6 } });
            Console.WriteLine("\n\tA: " + A.ToString());
            Console.WriteLine("\n\t\tA is_almost_symmetric (expect success): " + n.is_almost_symmetric(A));

            Matrix B = Matrix.from_list(new List<double[]>() { new double[] { 1, 2 }, new double[] { 3, 4 } });
            Console.WriteLine("\n\tB: " + B.ToString());
            Console.WriteLine("\n\t\tB is_almost_symmetric (expect fail): " + n.is_almost_symmetric(B));
        }
Ejemplo n.º 56
0
        /// <inheritdoc/>
        protected override Vector2F OnMeasure(Vector2F availableSize)
        {
            // Similar to UIControl.OnMeasure, but we sum up the desired sizes in the stack panel
            // orientation. In the other direction we take the maximum of the children - unless a
            // Width or Height was set explicitly. If there are VisualChildren that are not Children,
            // they do not contribute to the DesiredSize.

            float width     = Width;
            float height    = Height;
            bool  hasWidth  = Numeric.IsPositiveFinite(width);
            bool  hasHeight = Numeric.IsPositiveFinite(height);

            if (hasWidth && width < availableSize.X)
            {
                availableSize.X = width;
            }
            if (hasHeight && height < availableSize.Y)
            {
                availableSize.Y = height;
            }

            Vector4 padding = Padding;

            availableSize.X -= padding.X + padding.Z;
            availableSize.Y -= padding.Y + padding.W;

            foreach (var child in VisualChildren)
            {
                child.Measure(availableSize);
            }

            if (hasWidth && hasHeight)
            {
                return(new Vector2F(width, height));
            }

            Vector2F desiredSize = new Vector2F(width, height);

            float maxWidth  = 0;
            float sumWidth  = 0;
            float maxHeight = 0;
            float sumHeight = 0;

            // Sum up widths and heights.
            foreach (var child in Children)
            {
                float childWidth  = child.DesiredWidth;
                float childHeight = child.DesiredHeight;
                maxWidth   = Math.Max(maxWidth, childWidth);
                maxHeight  = Math.Max(maxHeight, childHeight);
                sumWidth  += childWidth;
                sumHeight += childHeight;
            }

            if (!hasWidth)
            {
                if (Orientation == Orientation.Horizontal)
                {
                    desiredSize.X = sumWidth;
                }
                else
                {
                    desiredSize.X = maxWidth;
                }
            }

            if (!hasHeight)
            {
                if (Orientation == Orientation.Vertical)
                {
                    desiredSize.Y = sumHeight;
                }
                else
                {
                    desiredSize.Y = maxHeight;
                }
            }

            desiredSize.X += padding.X + padding.Z;
            desiredSize.Y += padding.Y + padding.W;
            return(desiredSize);
        }
Ejemplo n.º 57
0
        public static void test_is_positive_definite()
        {
            Console.WriteLine("\nTesting is_positive_definite(Matrix A) ...\n");
            Numeric n = new Numeric();
            List<double[]> list1 = new List<double[]>() { new double[] { 1, 2 }, new double[] { 2, 1 } }; //false
            List<double[]> list2 = new List<double[]>() { new double[] { 2, -1, 0 }, new double[] { -1, 2, -1 }, new double[] { 0, -1, 2 } }; //true

            Console.Write("\n\tExpect Fail: is_positive_definite(" + Matrix.from_list(list1) + ") = ");
            Console.WriteLine(n.is_positive_definite(Matrix.from_list(list1)));
            Console.WriteLine("\tExpect True: is_positive_definite(" + Matrix.from_list(list2) + ") = " + n.is_positive_definite(Matrix.from_list(list2)));
        }
Ejemplo n.º 58
0
        /// <summary>
        /// multiplies 2 digits given their positions
        /// </summary>
        /// <param name="digit1"></param>
        /// <param name="digit2"></param>
        /// <param name="digit1Pos"></param>
        /// <param name="digit2Pos"></param>
        /// <returns></returns>
        private Numeric MultiplyDigits(string digit1, string digit2,
            Numeric digit1Pos, Numeric digit2Pos)
        {
            Debug.WriteLine("multiplying digits {0} and {1} at positions {2} and {3}",
                digit1, digit2, digit1Pos.SymbolsText, digit2Pos.SymbolsText);

            var val = this._multMap.Get(digit1, digit2);
            Debug.WriteLine("{0} * {1} = {2}",
                    digit1, digit2, val.SymbolsText);

            var rv = val.Clone().HasShift();
            var number1 = Numeric.New(this.NumberSystem, digit1).HasShift();
            var number2 = Numeric.New(this.NumberSystem, digit2).HasShift();

            var counter = digit1Pos.HasAddition();
            rv.ShiftRight(counter);
            number1.ShiftRight(counter);

            counter = digit2Pos.HasAddition();
            rv.ShiftRight(counter);
            number2.ShiftRight(counter);

            Debug.WriteLine("equivalent to {0} * {1} = {2}",
                    number1.SymbolsText, number2.SymbolsText, rv.SymbolsText);
            return rv.InnermostNumeric;
        }