/// <summary>
 /// Converts the given signed rational number to an array of bytes.
 /// Numbers are converted from the platform byte-order to the given byte-order.
 /// </summary>
 public static byte[] GetBytes(MathEx.Fraction32 value, ByteOrder tobyteorder)
 {
     byte[] num = GetBytes(value.Numerator, ByteOrder.System, tobyteorder);
     byte[] den = GetBytes(value.Denominator, ByteOrder.System, tobyteorder);
     byte[] data = new byte[8];
     Array.Copy(num, 0, data, 0, 4);
     Array.Copy(den, 0, data, 4, 4);
     return data;
 }
Exemplo n.º 2
0
 public static Color Lerp(Color a, Color b, double k)
 {
     k = MathEx.Clamp01(k);
     return(new Color(a.r + (b.r - a.r) * k, a.g + (b.g - a.g) * k, a.b + (b.b - a.b) * k, a.a + (b.a - a.a) * k));
 }
Exemplo n.º 3
0
        public void Solve()
        {
            var        n      = sc.Integer();
            var        a      = sc.Long(n);
            const long INF    = 10000000001;
            var        primes = MathEx.Sieve(220000);
            var        pp     = MathEx.SieveList(2200);

            foreach (long p in pp)
            {
                for (int i = 0; i < n; i++)
                {
                    while (a[i] % (p * p * p) == 0)
                    {
                        a[i] /= p * p * p;
                    }
                }
            }
            Debug.WriteLine(a.AsJoinedString());

            var xs   = a.Distinct().ToList(); xs.Sort();
            var m    = xs.Count;
            var cnt  = new int[m];
            var used = new bool[m];

            for (int i = 0; i < n; i++)
            {
                cnt[xs.BinarySearch(a[i])]++;
            }

            var ans = 0;

            for (int i = 0; i < m; i++)
            {
                if (xs[i] == 1)
                {
                    ans++; used[i] = true;
                }
                if (used[i])
                {
                    continue;
                }
                used[i] = true;

                var x = xs[i];
                var y = 1L;
                foreach (long p in pp)
                {
                    if (x % (p * p) == 0)
                    {
                        x /= (p * p); y = Math.Min(INF, y * p);
                    }
                    else if (x % p == 0)
                    {
                        x /= p; y = Math.Min(INF, y * p); y = Math.Min(INF, y * p);
                    }
                }
                if (x != 1)
                {
                    if (x < 200000 && primes[x])
                    {
                        y = Math.Min(INF, y * x); y = Math.Min(INF, y * x);
                    }
                    else
                    {
                        y = INF;
                    }
                }
                var pos = xs.BinarySearch(y);
                if (pos < 0)
                {
                    ans += cnt[i];
                }
                else
                {
                    ans += Math.Max(cnt[i], cnt[pos]); used[pos] = true;
                }
            }


            IO.Printer.Out.WriteLine(ans);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Triggered when the move snap increment value changes.
 /// </summary>
 /// <param name="value">Value that determines in what increments to perform move snapping.</param>
 private void OnMoveSnapValueChanged(float value)
 {
     Handles.MoveSnapAmount = MathEx.Clamp(value, 0.01f, 1000.0f);
     editorSettingsHash     = EditorSettings.Hash;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Creates the scene camera and updates the render texture. Should be called at least once before using the
        /// scene view. Should be called whenever the window is resized.
        /// </summary>
        /// <param name="width">Width of the scene render target, in pixels.</param>
        /// <param name="height">Height of the scene render target, in pixels.</param>
        private void UpdateRenderTexture(int width, int height)
        {
            width  = MathEx.Max(20, width);
            height = MathEx.Max(20, height);

            // Note: Depth buffer and readable flags are required because ScenePicking uses it
            Texture colorTex = Texture.Create2D(width, height, PixelFormat.R8G8B8A8, TextureUsage.Render | TextureUsage.CPUReadable);
            Texture depthTex = Texture.Create2D(width, height, PixelFormat.D32_S8X24, TextureUsage.DepthStencil | TextureUsage.CPUReadable);

            renderTexture          = new RenderTexture2D(colorTex, depthTex);
            renderTexture.Priority = 1;

            if (camera == null)
            {
                SceneObject sceneCameraSO = new SceneObject("SceneCamera", true);
                camera              = sceneCameraSO.AddComponent <Camera>();
                camera.Target       = renderTexture;
                camera.ViewportRect = new Rect2(0.0f, 0.0f, 1.0f, 1.0f);

                sceneCameraSO.Position = new Vector3(0, 0.5f, 1);
                sceneCameraSO.LookAt(new Vector3(0, 0.5f, 0));

                camera.Priority      = 2;
                camera.NearClipPlane = 0.05f;
                camera.FarClipPlane  = 2500.0f;
                camera.ClearColor    = ClearColor;
                camera.Layers        = UInt64.MaxValue & ~SceneAxesHandle.LAYER; // Don't draw scene axes in this camera

                cameraController = sceneCameraSO.AddComponent <SceneCamera>();

                renderTextureGUI = new GUIRenderTexture(renderTexture);
                rtPanel.AddElement(renderTextureGUI);

                sceneGrid      = new SceneGrid(camera);
                sceneSelection = new SceneSelection(camera);
                sceneGizmos    = new SceneGizmos(camera);
                sceneHandles   = new SceneHandles(this, camera);
            }
            else
            {
                camera.Target = renderTexture;
                renderTextureGUI.RenderTexture = renderTexture;
            }

            Rect2I rtBounds = new Rect2I(0, 0, width, height);

            renderTextureGUI.Bounds = rtBounds;
            focusCatcher.Bounds     = GUIUtility.CalculateBounds(rtPanel, GUI);

            sceneAxesGUI.SetPosition(width - HandleAxesGUISize - HandleAxesGUIPaddingX, HandleAxesGUIPaddingY);

            // TODO - Consider only doing the resize once user stops resizing the widget in order to reduce constant
            // render target destroy/create cycle for every single pixel.

            camera.AspectRatio = width / (float)height;

            if (profilerCamera != null)
            {
                profilerCamera.Target = renderTexture;
            }
        }
Exemplo n.º 6
0
        private static bool GetShouldKite()
        {
            if (Core.Buffs.HasInvulnerableShrine)
            {
                return(false);
            }

            if (Core.Player.IsInTown)
            {
                return(false);
            }

            if (!TrinityCombat.IsInCombat)
            {
                return(false);
            }

            if (TrinityCombat.Targeting.CurrentTarget != null && TrinityCombat.Targeting.CurrentTarget.IsTreasureGoblin)
            {
                return(false);
            }

            if (TrinityCombat.Routines.Current.ShouldIgnoreKiting())
            {
                Core.Logger.Debug(LogCategory.Avoidance, "Not Kiting because routine has said no");
                return(false);
            }

            if (TrinityCombat.Targeting.CurrentTarget?.Distance < 10f && GizmoProximityTypes.Contains(TrinityCombat.Targeting.CurrentTarget.Type))
            {
                Core.Logger.Debug(LogCategory.Avoidance, "Not Kiting because gizmo nearby");
                return(false);
            }

            if (DateTime.UtcNow < KiteStutterCooldownEndTime)
            {
                Core.Logger.Debug(LogCategory.Avoidance, "Kite On Cooldown");
                return(false);
            }

            var currentTarget       = TrinityCombat.Targeting.CurrentTarget;
            var isCloseLargeMonster = currentTarget?.Distance < 12f && (currentTarget.MonsterSize != MonsterSize.Big || currentTarget.MonsterSize != MonsterSize.Boss);

            if (PlayerMover.IsBlocked && !isCloseLargeMonster && Core.BlockedCheck.BlockedTime.TotalMilliseconds > 8000 && !Core.Avoidance.InCriticalAvoidance(ZetaDia.Me.Position))
            {
                Core.Logger.Log(LogCategory.Avoidance, "Not kiting because blocked");
                return(false);
            }

            var playerHealthPct = Core.Player.CurrentHealthPct * 100;

            if (playerHealthPct > 50 && TrinityCombat.Targeting.CurrentTarget != null)
            {
                // Restrict kiting when the current target is on the edge of line of sight
                // This should help with flip-flopping around corners and doorways.

                var from = Core.Player.Position;
                var to   = TrinityCombat.Targeting.CurrentTarget.Position;

                var losAngleA    = MathEx.WrapAngle((float)(MathUtil.FindDirectionRadian(from, to) - Math.Round(Math.PI, 5) / 2));
                var losPositionA = MathEx.GetPointAt(from, TrinityCombat.Targeting.CurrentTarget.Distance, losAngleA);
                if (!Core.Avoidance.Grid.CanRayCast(from, losPositionA))
                {
                    return(false);
                }

                var losAngleB    = MathEx.WrapAngle((float)(MathUtil.FindDirectionRadian(from, to) + Math.Round(Math.PI, 5) / 2));
                var losPositionB = MathEx.GetPointAt(from, TrinityCombat.Targeting.CurrentTarget.Distance, losAngleB);
                if (!Core.Avoidance.Grid.CanRayCast(from, losPositionB))
                {
                    return(false);
                }
            }

            var isAtKiteHealth = playerHealthPct <= TrinityCombat.Routines.Current.KiteHealthPct;

            if (isAtKiteHealth && TargetZDif < 4 && TrinityCombat.Routines.Current.KiteMode != KiteMode.Never)
            {
                var canSeeTarget = TrinityCombat.Targeting.CurrentTarget == null || Core.Avoidance.Grid.CanRayCast(ZetaDia.Me.Position, TrinityCombat.Targeting.CurrentTarget.Position);
                if (canSeeTarget)
                {
                    if (Core.Grids.Avoidance.IsStandingInFlags(AvoidanceFlags.KiteFrom))
                    {
                        if (DateTime.UtcNow.Subtract(LastKiteTime).TotalMilliseconds > TrinityCombat.Routines.Current.KiteStutterDelay)
                        {
                            Core.Logger.Debug(LogCategory.Avoidance, "Kite Shutter Triggered");
                            LastKiteTime = DateTime.UtcNow;
                            KiteStutterCooldownEndTime = DateTime.UtcNow.AddMilliseconds(TrinityCombat.Routines.Current.KiteStutterDuration);
                            return(true);
                        }

                        Core.Logger.Debug(LogCategory.Avoidance, "IsStandingInFlags... KiteFromNode");
                        LastAvoidTime = DateTime.UtcNow;
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 7
0
 public override bool Miller(double n, int iteration) => MathEx.Miller((long)n, iteration);
Exemplo n.º 8
0
        private void MovementUpdateInternal(float deltaTime)
        {
            // a = v/t, should probably expose as a variable
            var acceleration = MaxSpeed / 0.4f;

            // Get our current position. We read from transform.position as few times as possible as it is relatively slow
            // (at least compared to a local variable)
            var currentPosition = Tr.position;

            // Update which point we are moving towards
            _interpolator.MoveToCircleIntersection2D(currentPosition, _pickNextWaypointDist, _movementPlane);
            var dir = _movementPlane.ToPlane(SteeringTargetV3 - currentPosition);

            // Calculate the distance to the end of the path
            var distanceToEnd = dir.magnitude + MathEx.Max(0, _interpolator.remainingDistance);

            // Check if we have reached the target
            var prevTargetReached = TargetReached;

            TargetReached = distanceToEnd <= _endReachedDistance && _interpolator.valid;
            if (!prevTargetReached && TargetReached)
            {
                MovementCompleted();
            }
            // Check if we have a valid path to follow and some other script has not stopped the character
            float slowdown = 1;

            if (_interpolator.valid)
            {
                // How fast to move depending on the distance to the destination.
                // Move slower as the character gets closer to the destination.
                // This is always a value between 0 and 1.
                if (distanceToEnd < _slowdownDistance)
                {
                    slowdown          = Mathf.Sqrt(distanceToEnd / _slowdownDistance);
                    _slowLerp.Enabled = false;
                }
                else
                {
                    if (_interpolator.ShouldSlow())
                    {
                        if (!_slowLerp.Enabled)
                        {
                            _slowLerp.RestartLerp(1, 0, _slowdownTime);
                        }
                        slowdown = _slowLerp.GetLerpValue();
                    }
                    else
                    {
                        _slowLerp.Enabled = false;
                    }
                }
                if (TargetReached && _goToExactEndPoint)
                {
                    // Slow down as quickly as possible
                    _velocity2D -= Vector2.ClampMagnitude(_velocity2D, acceleration * deltaTime);
                }
                else
                {
                    // Normalized direction of where the agent is looking
                    var forwards = _movementPlane.ToPlane(Tr.rotation * Vector3.forward);
                    _velocity2D += MovementUtilities.CalculateAccelerationToReachPoint(dir, dir.normalized * MaxSpeed, _velocity2D, acceleration, _rotationSpeed, MaxSpeed, forwards) * deltaTime;
                }
            }
            else
            {
                slowdown = 1;
                // Slow down as quickly as possible
                _velocity2D -= Vector2.ClampMagnitude(_velocity2D, acceleration * deltaTime);
            }

            _velocity2D = MovementUtilities.ClampVelocity(
                _velocity2D, MaxSpeed, slowdown, _slowWhenNotFacingTarget,
                _movementPlane.ToPlane(Tr.forward));

            ApplyGravity(deltaTime);

            if (_rvoController != null && _rvoController.enabled)
            {
                // Send a message to the RVOController that we want to move
                // with this velocity. In the next simulation step, this
                // velocity will be processed and it will be fed back to the
                // rvo controller and finally it will be used by this script
                // when calling the CalculateMovementDelta method below

                // Make sure that we don't move further than to the end point
                // of the path. If the RVO simulation FPS is low and we did
                // not do this, the agent might overshoot the target a lot.
                var rvoTarget = currentPosition + _movementPlane.ToWorld(Vector2.ClampMagnitude(_velocity2D, distanceToEnd), 0f);
                _rvoController.SetTarget(rvoTarget, _velocity2D.magnitude, MaxSpeed);
            }

            Vector2 desiredRotationDirection;

            if (_rvoController != null && _rvoController.enabled)
            {
                // When using local avoidance, use the actual velocity we are moving with (delta2D/deltaTime) if that velocity
                // is high enough, otherwise fall back to the velocity that we want to move with (velocity2D).
                // The local avoidance velocity can be very jittery when the character is close to standing still
                // as it constantly makes small corrections. We do not want the rotation of the character to be jittery.
                //var actualVelocity = delta2D / deltaTime;
                var actualVelocity = _lastDeltaPosition / _lastDeltaTime;
                desiredRotationDirection = Vector2.Lerp(_velocity2D, actualVelocity, 4 * actualVelocity.magnitude / (MaxSpeed + 0.0001f));
            }
            else
            {
                desiredRotationDirection = _velocity2D;
            }
            var delta2D = _lastDeltaPosition = CalculateDeltaToMoveThisFrame(_movementPlane.ToPlane(currentPosition), distanceToEnd, deltaTime);

            // Rotate towards the direction we are moving in
            var currentRotationSpeed = _rotationSpeed * MathEx.Max(0, (slowdown - 0.3f) / 0.7f);

            RotateTowards(desiredRotationDirection, currentRotationSpeed * deltaTime);

            var deltaPosition = _movementPlane.ToWorld(delta2D, _verticalVelocity * deltaTime);

            Move(currentPosition, deltaPosition);
        }
        private static void Draw(ParticleSystem component)
        {
            SceneObject so = component.SceneObject;

            // Draw collision planes, if enabled
            Gizmos.Color = Color.Yellow;
            ParticleEvolver[] evolvers = component.Evolvers;
            foreach (var entry in evolvers)
            {
                if (entry is ParticleCollisions collisions)
                {
                    if (collisions.Options.mode == ParticleCollisionMode.Plane)
                    {
                        void DrawPlane(Vector3 position, Vector3 right, Vector3 up, Vector3 forward)
                        {
                            Vector3 topLeft  = position - right + up;
                            Vector3 topRight = position + right + up;
                            Vector3 botLeft  = position - right - up;
                            Vector3 botRight = position + right - up;

                            Gizmos.DrawLine(topLeft, topRight);
                            Gizmos.DrawLine(topRight, botRight);
                            Gizmos.DrawLine(botRight, botLeft);
                            Gizmos.DrawLine(botLeft, topLeft);

                            Gizmos.DrawLine(position, position + forward * 0.4f);
                        }

                        SceneObject[] planeObjects = collisions.PlaneObjects;
                        foreach (var planeSO in planeObjects)
                        {
                            Vector3 position = planeSO.Position;
                            Vector3 right    = planeSO.Rotation.Rotate(Vector3.XAxis);
                            Vector3 up       = planeSO.Rotation.Rotate(Vector3.YAxis);
                            Vector3 forward  = planeSO.Forward;

                            DrawPlane(position, right, up, forward);
                        }

                        Plane[] planes = collisions.Planes;
                        foreach (var plane in planes)
                        {
                            Vector3 right, up;
                            Vector3.OrthogonalComplement(plane.normal, out right, out up);

                            DrawPlane(plane.normal * plane.d, right, up, plane.normal);
                        }
                    }
                }
            }

            // Draw emitter shapes
            Gizmos.Transform = Matrix4.TRS(so.Position, Quaternion.LookRotation(so.Rotation.Forward, so.Rotation.Up), Vector3.One);
            Gizmos.Color     = Color.Green;

            ParticleEmitter[] emitters = component.Emitters;
            foreach (var entry in emitters)
            {
                ParticleEmitterShape shape = entry?.Shape;
                if (shape == null)
                {
                    continue;
                }

                if (shape is ParticleEmitterBoxShape boxShape)
                {
                    Gizmos.DrawWireCube(Vector3.Zero, boxShape.Options.extents);
                }
                else if (shape is ParticleEmitterSphereShape sphereShape)
                {
                    ParticleSphereShapeOptions options = sphereShape.Options;
                    Gizmos.DrawWireSphere(Vector3.Zero, options.radius);

                    if (options.thickness > 0.0f)
                    {
                        float innerRadius = options.radius * (1.0f - MathEx.Clamp01(options.thickness));
                        if (options.thickness < 1.0f)
                        {
                            Gizmos.Color = Color.Green * new Color(0.5f, 0.5f, 0.5f);
                            Gizmos.DrawWireSphere(Vector3.Zero, innerRadius);
                        }

                        Gizmos.Color = Color.Green * new Color(0.25f, 0.25f, 0.25f);
                        Gizmos.DrawLine(Vector3.XAxis * innerRadius, Vector3.XAxis * options.radius);
                        Gizmos.DrawLine(-Vector3.XAxis * innerRadius, -Vector3.XAxis * options.radius);
                        Gizmos.DrawLine(Vector3.YAxis * innerRadius, Vector3.YAxis * options.radius);
                        Gizmos.DrawLine(-Vector3.YAxis * innerRadius, -Vector3.YAxis * options.radius);
                        Gizmos.DrawLine(Vector3.ZAxis * innerRadius, Vector3.ZAxis * options.radius);
                        Gizmos.DrawLine(-Vector3.ZAxis * innerRadius, -Vector3.ZAxis * options.radius);
                    }
                }
                else if (shape is ParticleEmitterHemisphereShape hemisphereShape)
                {
                    ParticleHemisphereShapeOptions options = hemisphereShape.Options;
                    Gizmos.DrawWireHemisphere(Vector3.Zero, options.radius);
                    DrawArcWithThickness(Vector3.Zero, options.radius, new Degree(360.0f), options.thickness, Color.Green);

                    if (options.thickness > 0.0f)
                    {
                        float innerRadius = options.radius * (1.0f - MathEx.Clamp01(options.thickness));
                        if (options.thickness < 1.0f)
                        {
                            Gizmos.Color = Color.Green * new Color(0.5f, 0.5f, 0.5f);
                            Gizmos.DrawWireHemisphere(Vector3.Zero, innerRadius);
                        }

                        Gizmos.Color = Color.Green * new Color(0.25f, 0.25f, 0.25f);
                        Gizmos.DrawLine(Vector3.XAxis * innerRadius, Vector3.XAxis * options.radius);
                        Gizmos.DrawLine(-Vector3.XAxis * innerRadius, -Vector3.XAxis * options.radius);
                        Gizmos.DrawLine(Vector3.YAxis * innerRadius, Vector3.YAxis * options.radius);
                        Gizmos.DrawLine(-Vector3.YAxis * innerRadius, -Vector3.YAxis * options.radius);
                        Gizmos.DrawLine(Vector3.ZAxis * innerRadius, Vector3.ZAxis * options.radius);
                    }
                }
                else if (shape is ParticleEmitterCircleShape circleShape)
                {
                    ParticleCircleShapeOptions options = circleShape.Options;
                    DrawArcWithThickness(Vector3.Zero, options.radius, options.arc, options.thickness, Color.Green);
                }
                else if (shape is ParticleEmitterLineShape lineShape)
                {
                    float halfLength = lineShape.Options.length * 0.5f;
                    Gizmos.DrawLine(new Vector3(-halfLength, 0.0f, 0.0f), new Vector3(halfLength, 0.0f, 0.0f));
                }
                else if (shape is ParticleEmitterRectShape rectShape)
                {
                    Vector2 extents = rectShape.Options.extents;
                    Vector3 right   = new Vector3(extents.x, 0.0f, 0.0f);
                    Vector3 up      = new Vector3(0.0f, extents.y, 0.0f);

                    Vector3 topLeft  = -right + up;
                    Vector3 topRight = right + up;
                    Vector3 botLeft  = -right - up;
                    Vector3 botRight = right - up;

                    Gizmos.DrawLine(topLeft, topRight);
                    Gizmos.DrawLine(topRight, botRight);
                    Gizmos.DrawLine(botRight, botLeft);
                    Gizmos.DrawLine(botLeft, topLeft);
                }
                else if (shape is ParticleEmitterConeShape coneShape)
                {
                    ParticleConeShapeOptions options = coneShape.Options;

                    float  topRadius  = options.radius;
                    float  baseRadius = options.length * MathEx.Tan(options.angle);
                    Radian arc        = options.arc;

                    if (topRadius > 0.0f)
                    {
                        DrawArcWithThickness(Vector3.Zero, topRadius, arc, options.thickness, Color.Green);
                    }

                    DrawArcWithThickness(new Vector3(0.0f, 0.0f, -options.length), baseRadius, arc, options.thickness,
                                         Color.Green);

                    Gizmos.Color = Color.Green;
                    DrawConeBorder(topRadius, baseRadius, arc, options.length);

                    if (options.thickness > 0.0f && options.thickness < 1.0f)
                    {
                        Gizmos.Color = Color.Green * new Color(0.5f, 0.5f, 0.5f);
                        DrawConeBorder(
                            topRadius * (1.0f - MathEx.Clamp01(options.thickness)),
                            baseRadius * (1.0f - MathEx.Clamp01(options.thickness)), arc, options.length);
                    }
                }
                else if (shape is ParticleEmitterStaticMeshShape staticMeshShape)
                {
                    RRef <Mesh> mesh = staticMeshShape.Options.mesh;
                    if (mesh.IsLoaded)
                    {
                        Gizmos.DrawWireMesh(mesh.Value.MeshData);
                    }
                }
                else if (shape is ParticleEmitterSkinnedMeshShape skinnedMeshShape)
                {
                    Renderable renderable = skinnedMeshShape.Options.renderable;
                    if (renderable != null)
                    {
                        RRef <Mesh> mesh = renderable.Mesh;
                        if (mesh.IsLoaded)
                        {
                            Gizmos.DrawWireMesh(mesh.Value.MeshData);
                        }
                    }
                }
            }

            // Draw manual bounds
            if (!component.Settings.UseAutomaticBounds)
            {
                Gizmos.Color = Color.LightGray;

                AABox bounds = component.Settings.CustomBounds;
                Gizmos.DrawWireCube(bounds.Center, bounds.Size * 0.5f);
            }
        }
        private IEnumerable <ICandle> GenerateCandles(
            AssetPair assetPair,
            CandlePriceType priceType,
            DateTime exclusiveStartDate,
            DateTime exclusiveEndDate,
            decimal exclusiveStartPrice,
            decimal exclusiveEndPrice,
            decimal spread)
        {
            var start = exclusiveStartDate.AddSeconds(1);
            var end   = exclusiveEndDate.AddSeconds(-1);

            if (exclusiveEndDate - exclusiveStartDate <= TimeSpan.FromSeconds(1))
            {
                yield break;
            }

            var duration  = (decimal)(exclusiveEndDate - exclusiveStartDate).TotalSeconds;
            var prevClose = exclusiveStartPrice;
            var trendSign = exclusiveStartPrice < exclusiveEndPrice ? 1 : -1;
            // Absolute start to end price change in % of start price
            var totalPriceChange = exclusiveStartPrice != 0m
                ? Math.Abs((exclusiveEndPrice - exclusiveStartPrice) / exclusiveStartPrice)
                : Math.Abs(exclusiveEndPrice - exclusiveStartPrice);
            var stepPriceChange = totalPriceChange / duration;
            var effectiveSpread = spread != 0
                ? Math.Abs(spread)
                : totalPriceChange * 0.2m;
            // Start in opposite dirrection
            var currentTrendSign = -trendSign;

            if (effectiveSpread == 0)
            {
                if (exclusiveStartPrice != 0)
                {
                    effectiveSpread = exclusiveStartPrice * 0.2m;
                }
                else if (exclusiveEndPrice != 0)
                {
                    effectiveSpread = exclusiveEndPrice * 0.2m;
                }
                else
                {
                    effectiveSpread = (decimal)Math.Pow(10, -assetPair.Accuracy / 4d);
                }
            }

            if (stepPriceChange == 0)
            {
                stepPriceChange = effectiveSpread / duration;
            }

            var backupMid = exclusiveStartPrice;

            if (backupMid == 0)
            {
                backupMid = exclusiveEndPrice != 0 ? exclusiveEndPrice : effectiveSpread;
            }

            //File.WriteAllLines(@"C:\temp\candles.csv", new[]
            //{
            //    "timestamp,t,mid,min,max,open,close,low,high,closePriceMaxDeviation,rangeMinMaxDeviationFactor,height"
            //});

            for (var timestamp = start; timestamp <= end; timestamp = timestamp.AddSeconds(1))
            {
                // Interpolation parameter (0..1)
                var t = (decimal)(timestamp - exclusiveStartDate).TotalSeconds / duration;

                // Lineary interpolated price for current candle
                var mid = MathEx.Lerp(exclusiveStartPrice, exclusiveEndPrice, t);

                if (mid <= 0)
                {
                    mid = backupMid;
                }

                var halfSpread = effectiveSpread * 0.5m;

                // Next candle opens at prev candle close and from 5% up to 50% of stepPriceChange,
                // direction is dependent of trend sign
                var open = prevClose + stepPriceChange * _rnd.NextDecimal(0.05m, 0.5m) * currentTrendSign;

                if (open <= 0)
                {
                    open = mid;
                }

                // Lets candles goes from 10% near the generated range boundaries and
                // up to 100% of the spread in the middle of the generated range,
                // and only inside the spread at the range boundaries
                var rangeMinMaxDeviationFactor = MathEx.Lerp(0.1m, 1m, 2m * (0.5m - Math.Abs(0.5m - t)));
                var min = mid - halfSpread * rangeMinMaxDeviationFactor;
                var max = mid + halfSpread * rangeMinMaxDeviationFactor;

                if (min <= 0)
                {
                    min = mid;
                }

                var maxClosePriceDeviation = CalculateMaxClosePriceDeviation(currentTrendSign, open, mid, min, max);

                // Candle can be closed from the 10% and up to closePriceMaxDeviation% of price change from the open price
                // But only inside min/max and if it touched min/max, the sign will be changed, and close price will be regenerated

                decimal GenerateClose(decimal sign)
                {
                    return(open + stepPriceChange * _rnd.NextDecimal(0.05m, maxClosePriceDeviation) * sign);
                }

                var close = GenerateClose(currentTrendSign);

                if (close >= max && currentTrendSign > 0 ||
                    close <= min && currentTrendSign < 0)
                {
                    currentTrendSign = -currentTrendSign;

                    close = GenerateClose(currentTrendSign);
                }

                if (close <= 0)
                {
                    close = mid;
                }

                // Max low/high deviation from open/close is 20% - 50% of candle height, depending of current trend sign
                var height = Math.Abs(open - close);
                var high   = Math.Max(open, close) + _rnd.NextDecimal(0m, currentTrendSign > 0 ? 0.5m : 0.2m) * height;
                var low    = Math.Min(open, close) - _rnd.NextDecimal(0m, currentTrendSign < 0 ? 0.5m : 0.2m) * height;

                if (low <= 0)
                {
                    low = Math.Min(open, close);
                }

                if (high <= 0)
                {
                    high = Math.Max(open, close);
                }

                //File.AppendAllLines(@"C:\temp\candles.csv", new []
                //{
                //    $"{timestamp},{t},{mid},{min},{max},{open},{close},{low},{high},{maxClosePriceDeviation},{rangeMinMaxDeviationFactor},{height}"
                //});

                var newCandle = Candle.Create(
                    assetPair.Id,
                    priceType,
                    CandleTimeInterval.Sec,
                    timestamp,
                    (double)Math.Round(open, assetPair.Accuracy),
                    (double)Math.Round(close, assetPair.Accuracy),
                    (double)Math.Round(high, assetPair.Accuracy),
                    (double)Math.Round(low, assetPair.Accuracy),
                    0,
                    0,
                    0,
                    timestamp);

                if (open == 0 || close == 0 || high == 0 || low == 0)
                {
                    var context = new
                    {
                        AssetPair = new
                        {
                            assetPair.Id,
                            assetPair.Accuracy
                        },
                        exclusiveStartDate,
                        exclusiveEndDate,
                        start,
                        end,
                        exclusiveStartPrice,
                        exclusiveEndPrice,
                        duration,
                        spread,
                        effectiveSpread,
                        prevClose,
                        trendSign,
                        totalPriceChange,
                        timestamp,
                        t,
                        mid,
                        halfSpread,
                        currentTrendSign,
                        rangeMinMaxDeviationFactor,
                        min,
                        max,
                        height
                    };

                    throw new InvalidOperationException($"Generated candle {newCandle.ToJson()} has zero prices. Context: {context.ToJson()}");
                }

                prevClose = close;

                yield return(newCandle);
            }
        }
Exemplo n.º 11
0
 public static float CalculateJumpVelocity(float gravity, float jumpHeight)
 {
     //Calculates the jump height based on the given paramaters.
     return(MathEx.Sqrt(2 * gravity * jumpHeight));
 }
Exemplo n.º 12
0
 public static Point <T> Center(this BoundingBox <T> self)
 {
     return(new Point <T>(MathEx.Average(self.X1, self.X2), MathEx.Average(self.Y1, self.Y2)));
 }
Exemplo n.º 13
0
 public static Point <T> ProjectOnto(this Point <T> p, BoundingBox bbox)
 {
     return(new Point <T>(MathEx.InRange(p.X, bbox.X1, bbox.X2), MathEx.InRange(p.X, bbox.X1, bbox.X2)));
 }
Exemplo n.º 14
0
 public static Point <T> ProjectOnto <T>(this Point <T> p, BoundingBox <T> bbox) where T : IConvertible, IComparable <T>, IEquatable <T>
 {
     return(new Point <T>(MathEx.InRange(p.X, bbox.X1, bbox.X2), MathEx.InRange(p.X, bbox.X1, bbox.X2)));
 }
 public ExifSRationalArray(ExifTag tag, MathEx.Fraction32[] value)
     : base(tag)
 {
     mValue = value;
 }
Exemplo n.º 16
0
        public static async Task <bool> Run()
        {
            // NOT TESTED

            #region Spell Filters
            /// 532, 1837, 2794, 5445, 7931, 9076, 9338, 9490, 2441

            HashSet <uint> Spells = new HashSet <uint>()
            {
                //1st boss 100 tonze swing
                //10176 liquid capace (constant spewing attack, needs to run away)
                //2nd boss Reapders gale
                //10599. 10187 <45.62811, -26, -105.941> or Current XYZ: <50.26293, -26, -111.4103>
                11541, 10192                 //Hell of Water by Genbu
                , 10193, 10194               //Hell of Waste by Genbu
                //,10196,10197 //Sinister Tide (Arrow Mechanic)
            };
            #endregion

            #region Custom Mechanics



            HashSet <uint> HellOfWater = new HashSet <uint>()
            {
                11541, 10192
            };
            if (HellOfWater.IsCasting())
            {
                //Avoider(AvoiderType.Spell, 11541); //Sidestep should have this =\
                //Avoider(AvoiderType.Spell, 10192);

                //Vector3 _loc = new Vector3 GetRandomPointInCircle(55, -88, -461,3f);

//                while (Core.Me.Distance(_loc) > 1f)
//              {
                await CommonTasks.MoveTo(MathEx.GetRandomPointInCircle(Core.Me.Location, 3f));

                await Coroutine.Yield();

                //            }

                await Coroutine.Sleep(3000);

                if (ActionManager.IsSprintReady)
                {
                    ActionManager.Sprint();
                    await Coroutine.Wait(1000, () => !ActionManager.IsSprintReady);
                }
                Stopwatch sw = new Stopwatch();
                sw.Start();
                //Logging.Write(Colors.Aquamarine, $"Ancient Flare Handling");

                await Coroutine.Sleep(1000);

                await Coroutine.Yield();

                sw.Stop();
            }

            HashSet <uint> HellOfWaste2 = new HashSet <uint>()
            {
                10194, 10193
            };
            if (HellOfWaste2.IsCasting())
            {
                await CommonTasks.MoveTo(MathEx.GetRandomPointInCircle(Core.Me.Location, 3f));

                await Coroutine.Yield();


                await Coroutine.Sleep(3000);

                if (ActionManager.IsSprintReady)
                {
                    ActionManager.Sprint();
                    await Coroutine.Wait(1000, () => !ActionManager.IsSprintReady);
                }
                Stopwatch sw = new Stopwatch();
                sw.Start();
                //Logging.Write(Colors.Aquamarine, $"Ancient Flare Handling");

                await Coroutine.Sleep(1000);

                await Coroutine.Yield();

                sw.Stop();
            }


            #endregion

            /// Default (缺省)
            if (Spells.IsCasting())
            {
                Core.Me.ClearTarget();                                          //Logging.Write(Colors.Aquamarine, $"Default Spell Handling");
                while (Core.Me.Location.Distance2D(PartyManager.VisibleMembers.Where(x => !x.IsMe && x.BattleCharacter.IsAlive).FirstOrDefault().BattleCharacter.Location) > 0.5)
                {
                    MovementManager.SetFacing(PartyManager.VisibleMembers.Where(x => !x.IsMe && x.BattleCharacter.IsAlive).FirstOrDefault().BattleCharacter.Location);
                    MovementManager.MoveForwardStart();
                    await Coroutine.Sleep(100);

                    MovementManager.MoveStop();
                }
                //await Coroutine.Sleep(1000);
                await Coroutine.Yield();;
            }

            /// SideStep (回避)
            //if (WorldManager.SubZoneId != 2996) { Helpers.BossIds.ToggleSideStep(new uint[] { 8210 }); } else { Helpers.BossIds.ToggleSideStep(); }

            return(false);
        }
        public TrinityPower GetOffensivePower()
        {
            Vector3 position;

            var allUnits = Core.Targets.ByType[TrinityObjectType.Unit].Where(u => u.IsUnit && u.RadiusDistance <= 50f).ToList();

            var clusterUnits =
                (from u in allUnits
                 where u.IsUnit && u.Weight > 0 && !u.IsPlayer
                 orderby
                 u.NearbyUnitsWithinDistance(15f) descending,
                 u.Distance,
                 u.HitPointsPct descending
                 select u).ToList();

            var bestClusterUnit = clusterUnits.FirstOrDefault();

            //10 second 60% damage reduction should always be on to survive
            if (!HasJeramsRevengeBuff && Player.CurrentHealthPct > 0.4 && !Core.Avoidance.InCriticalAvoidance(Player.Position) &&
                (ZetaDia.Me.IsInCombat || Player.CurrentHealthPct < 0.4) && bestClusterUnit != null && Skills.WitchDoctor.WallOfDeath.CanCast())
            {
                return(WallOfDeath(allUnits.FirstOrDefault()));
            }

            if (bestClusterUnit != null)
            {
                if (Player.HasBuff(SNOPower.Witchdoctor_Hex))
                {
                    Vector3 explodePos = PlayerMover.IsBlocked ? Player.Position : bestClusterUnit.Position;
                    return(ExplodeChicken(explodePos));
                }

                if (!HasJeramsRevengeBuff && ZetaDia.Me.IsInCombat && Skills.WitchDoctor.WallOfDeath.CanCast())
                {
                    var target = allUnits.FirstOrDefault();
                    if (target != null)
                    {
                        return(WallOfDeath(target));
                    }
                }

                // Make sure we approach carefully when our defenses are down
                var harvestStacks      = Skills.WitchDoctor.SoulHarvest.BuffStacks;
                var bestHarvestCluster = TargetUtil.GetBestClusterPoint(18f, 50f);
                if (Core.Rift.IsGreaterRift && harvestStacks < 10 && Legendary.LakumbasOrnament.IsEquipped)
                {
                    if (Skills.WitchDoctor.SpiritWalk.CanCast() && TargetUtil.ClusterExists(18f, 50f, 2))
                    {
                        return(SpiritWalk());
                    }

                    if (Skills.WitchDoctor.SpiritWalk.IsBuffActive && bestHarvestCluster != null)
                    {
                        return(Walk(bestHarvestCluster));
                    }
                }

                // SpiritWalk for the invulnerability
                var shouldBecomeInvulnerable = Core.Avoidance.Avoider.ShouldAvoid || Core.Avoidance.Avoider.ShouldKite || (Player.CurrentHealthPct < 0.9f && Core.Rift.IsGreaterRift);
                if (Skills.WitchDoctor.SpiritWalk.CanCast() && Settings.SpiritWalk.UseMode == UseTime.Default && TargetUtil.AnyMobsInRange(20f))
                {
                    return(SpiritWalk());
                }

                // Spam hex for the 50% damage reduction
                var closeUnit = HostileMonsters.FirstOrDefault(u => u.Distance < 40f);
                if (!Player.HasBuff(SNOPower.Witchdoctor_Hex) && Skills.WitchDoctor.Hex.CanCast() && closeUnit != null)
                {
                    return(Hex(TargetUtil.GetBestClusterPoint(15f, 20f)));
                }

                var targetsWithoutLocust     = clusterUnits.Where(u => !u.HasDebuff(SNOPower.Witchdoctor_Locust_Swarm)).OrderBy(u => u.Distance);
                var isAnyTargetWithLocust    = clusterUnits.Any(u => u.HasDebuff(SNOPower.Witchdoctor_Locust_Swarm) && u.Distance < 45f);
                var percentTargetsWithHaunt  = TargetUtil.DebuffedPercent(SNOPower.Witchdoctor_Haunt, 8f);
                var percentTargetsWithLocust = TargetUtil.DebuffedPercent(SNOPower.Witchdoctor_Locust_Swarm, 12f);
                var isEliteWithoutHaunt      = clusterUnits.Any(u => u.IsElite && !u.HasDebuff(SNOPower.Witchdoctor_Haunt) && u.Distance <= 20f);
                var isElitewithoutLocust     = clusterUnits.Any(u => u.IsElite && !u.HasDebuff(SNOPower.Witchdoctor_Locust_Swarm) && u.Distance <= 20f);
                var harvestBuffCooldown      = Core.Cooldowns.GetBuffCooldown(SNOPower.Witchdoctor_SoulHarvest);
                var harvestPossibleStackGain = 10 - harvestStacks;
                var harvestUnitsInRange      = allUnits.Count(u => u.Distance < 12f);
                var interruptForHarvest      = Skills.WitchDoctor.SoulHarvest.CanCast() && harvestPossibleStackGain >= harvestUnitsInRange && harvestBuffCooldown?.Remaining.TotalMilliseconds < 500;
                var interruptForHaunt        = percentTargetsWithHaunt < 0.2f || isEliteWithoutHaunt;
                var needToSwarmElite         = isElitewithoutLocust && !((Legendary.VileHive.IsEquipped || Runes.WitchDoctor.Pestilence.IsActive) && isAnyTargetWithLocust);
                var interruptForLocust       = (percentTargetsWithLocust < 0.1f || needToSwarmElite) && Player.PrimaryResource > 300 && Skills.WitchDoctor.LocustSwarm.CanCast();
                var interruptForHex          = Skills.WitchDoctor.Hex.CanCast();
                var interruptForSpiritWalk   = Skills.WitchDoctor.SpiritWalk.CanCast() && Settings.SpiritWalk.UseMode == UseTime.Default && shouldBecomeInvulnerable;

                // continue channelling firebats?
                if (Player.IsChannelling)
                {
                    if (!interruptForHaunt && !interruptForLocust && !interruptForHarvest && !interruptForHex && !interruptForSpiritWalk)
                    {
                        return(new TrinityPower(SNOPower.Witchdoctor_Firebats, 30f, Player.Position, 75, 250));
                    }
                }

                // Emergency health situation
                if (Player.CurrentHealthPct < 0.35)
                {
                    if (Skills.WitchDoctor.SpiritWalk.CanCast())
                    {
                        return(SpiritWalk());
                    }

                    if (TargetUtil.AnyMobsInRange(12f) && Skills.WitchDoctor.SoulHarvest.CanCast())
                    {
                        return(SoulHarvest());
                    }

                    if (!HasJeramsRevengeBuff && Skills.WitchDoctor.WallOfDeath.CanCast() && allUnits.Any())
                    {
                        return(WallOfDeath(allUnits.FirstOrDefault()));
                    }
                }

                // Soul harvest for the damage reduction of Okumbas Ornament
                if (Skills.WitchDoctor.SoulHarvest.CanCast() && (bestClusterUnit.Distance < 12f || harvestStacks < 4 && TargetUtil.AnyMobsInRange(10f)) && harvestStacks < 10)
                {
                    if (harvestPossibleStackGain <= harvestUnitsInRange)
                    {
                        return(SoulHarvest());
                    }
                }

                // Locust
                if (Skills.WitchDoctor.LocustSwarm.CanCast() && Skills.WitchDoctor.LocustSwarm.TimeSinceUse > 1000 && targetsWithoutLocust.Any() && (!Runes.WitchDoctor.Pestilence.IsActive || !isAnyTargetWithLocust))
                {
                    if ((percentTargetsWithLocust < Settings.LocustPct || needToSwarmElite) && Player.PrimaryResource > 300 && targetsWithoutLocust.Any())
                    {
                        return(new TrinityPower(SNOPower.Witchdoctor_Locust_Swarm, 10f, targetsWithoutLocust.First().AcdId, 0, 0));
                    }
                }

                if (ShouldBigBadVoodoo(out position))
                {
                    return(BigBadVoodoo(position));
                }

                // Piranhas
                if (Skills.WitchDoctor.Piranhas.CanCast() && Player.PrimaryResource >= 250 &&
                    (TargetUtil.ClusterExists(15f, 40f) || TargetUtil.AnyElitesInRange(40f)) && Player.PrimaryResource >= 250)
                {
                    return(Piranhas(TargetUtil.GetBestClusterUnit()));
                }

                // .80 of mobs give or take. Spelltracker check is to prevent repeat casts ont he same target before the projectile arrives.
                var targetsWithoutHaunt = clusterUnits.Where(u => !u.HasDebuff(SNOPower.Witchdoctor_Haunt) && !SpellTracker.IsUnitTracked(u, SNOPower.Witchdoctor_Haunt)).OrderBy(u => u.Distance);
                if ((percentTargetsWithHaunt < Settings.HauntPct || isEliteWithoutHaunt) && targetsWithoutHaunt.Any() && Player.PrimaryResource > 100)
                {
                    var target = targetsWithoutHaunt.First();
                    return(Haunt(target));
                }

                Vector3 bestBuffedPosition;
                TargetUtil.BestBuffPosition(16f, bestClusterUnit.Position, true, out bestBuffedPosition);
                var bestClusterUnitRadiusPosition = MathEx.GetPointAt(bestClusterUnit.Position, bestClusterUnit.CollisionRadius * 1.1f, bestClusterUnit.Rotation);
                var bestFirebatsPosition          = bestBuffedPosition != Vector3.Zero ? bestBuffedPosition : bestClusterUnitRadiusPosition;
                var distance = bestFirebatsPosition.Distance2D(Player.Position);

                // Walk into cluster or buffed location.
                if (distance > 10f && distance < 35f && !PlayerMover.IsBlocked)
                {
                    if (distance > 20f && Skills.WitchDoctor.SpiritWalk.CanCast())
                    {
                        return(SpiritWalk());
                    }

                    //Core.Logger.Warn($"Walking to cluster position. Dist: {bestFirebatsPosition.Distance(Player.Position)}");
                    return(new TrinityPower(SNOPower.Walk, 3f, bestFirebatsPosition, 0, 0));
                }

                if (Skills.WitchDoctor.Firebats.CanCast())
                {
                    var closestUnit = allUnits.OrderBy(u => u.Distance).FirstOrDefault();
                    if (closestUnit != null)
                    {
                        return(Firebats(closestUnit));
                    }
                }
            }

            return(Walk(TargetUtil.GetLoiterPosition(CurrentTarget, 15f)));
        }
Exemplo n.º 18
0
        /// <summary>
        /// Does the input values check. If there are errors, the offending textbox will be focussed.
        /// </summary>
        /// <returns><c>true</c> if all analysis parameters are ok</returns>
        private bool DoCheckInput()
        {
            double doubleValue;
            double lpcutoff;
            double hpcutoff;
            double f0, fc, bandwith;
            double fcomputeMin = -1;
            double fcomputeMax = -1;

            // check filename and signal index
            if (signalsComboBox.Items.Count < 1)
            {
                textBox.Text = "You have to select a valid EDF inputfile first";
                textBoxInputFilename.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("You have to select a valid EDF inputfile first", NeuroLoopGainController.DefaultErrorMessageId);
                return(false);
            }

            if (signalsComboBox.SelectedIndex < 0)
            {
                signalsComboBox.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("No input signal selected", NeuroLoopGainController.DefaultErrorMessageId);
                return(false);
            }

            // check lowest LP and highest HP filter values
            if (!IsValidFloat(textBoxLP, out lpcutoff))
            {
                textBoxLP.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("Invalid LP filter value", NeuroLoopGainController.DefaultErrorMessageId);
                return(false);
            }

            if (!IsValidFloat(textBoxHP, out hpcutoff))
            {
                textBoxHP.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("Invalid HP filter value", NeuroLoopGainController.DefaultErrorMessageId);
                return(false);
            }

            if ((lpcutoff <= 0) || (lpcutoff <= hpcutoff))
            {
                textBoxLP.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("Low Pass filter cutoff must be 0 <= HP < LP", NeuroLoopGainController.DefaultErrorMessageId);
                return(false);
            }

            double signalSFreq = _edfFile.SignalInfo[signalsComboBox.SelectedIndex].NrSamples / _edfFile.FileInfo.SampleRecDuration;

            if (hpcutoff >= signalSFreq / 2)
            {
                textBoxHP.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add(string.Format("High Pass filter cutoff must be less than Nyquist frequency {0}", signalSFreq / 2), NeuroLoopGainController.DefaultErrorMessageId);
                return(false);
            }

            // check F0, B0, Fc and smoother rate values
            if (!IsValidFloat(textBoxF0, out f0))
            {
                textBoxF0.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("Invalid F0 parameter", NeuroLoopGainController.DefaultErrorMessageId);
            }

            if (!IsValidFloat(textBoxFc, out fc))
            {
                textBoxFc.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("Invalid Fc parameter", NeuroLoopGainController.DefaultErrorMessageId);
            }

            if (!IsValidFloat(textBoxB, out bandwith))
            {
                textBoxB.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("Invalid bandwidth parameter", NeuroLoopGainController.DefaultErrorMessageId);
            }

            if (!IsValidFloat(textBoxSmootherrate, out doubleValue))
            {
                textBoxSmootherrate.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("Invalid smooth rate parameter", NeuroLoopGainController.DefaultErrorMessageId);
            }

            // Check filter values versus SafetyFactor
            if (!NeuroLoopGainController.AppController.ApplicationError.Signaled)
            {
                // Calculate min and max values for Fcompute
                fcomputeMin = _configuration.SafetyFactor * Math.Max(f0, fc); // Safety factor (default) of 3 actually is an approximation of 1.5 * 2. (1.5 due to the use of non-ideal filters with some bandwidth)
                fcomputeMax = Math.Min(2 * 0.75 * lpcutoff, signalSFreq);     // Related with white noise spectra assumption. 0.75 is a safety factor due to the use of non-ideal filters
                if (!(fcomputeMin <= fcomputeMax))
                {
                    NeuroLoopGainController.AppController.ApplicationError.Add("No valid filters set-up. " +
                                                                               "F0 and/or Fc too large, or LP too small", NeuroLoopGainController.DefaultErrorMessageId);
                }
                // Check HP filter
                if (!(hpcutoff < _configuration.SafetyFactor * f0))
                {
                    NeuroLoopGainController.AppController.ApplicationError.Add(string.Format("HP filter should be < {0} Hz", _configuration.SafetyFactor * f0), NeuroLoopGainController.DefaultErrorMessageId);
                }
                // Check B < 2*F0
                if (!(bandwith < 2 * f0))
                {
                    NeuroLoopGainController.AppController.ApplicationError.Add("Bandwidth should be < 2*F0", NeuroLoopGainController.DefaultErrorMessageId);
                }

                //check smooth time
                if (!IsValidFloat(textBoxAnalysisPeriod, out doubleValue))
                {
                    textBoxAnalysisPeriod.Focus();
                    NeuroLoopGainController.AppController.ApplicationError.Add("Value for analysis time is not valid", NeuroLoopGainController.DefaultErrorMessageId);
                }
                if (((1 / doubleValue) > signalSFreq) || ((1 / doubleValue) < 1))
                {
                    /*
                     * 1. Sampling rate of the output cannot be higher than sampling rate of input
                     * 2. In the current version sampling rate of the outupt should be equal of higher than l Hz
                     */
                    textBoxAnalysisPeriod.Focus();
                    NeuroLoopGainController.AppController.ApplicationError.Add("Analysis time should be between " + string.Format("{0}", 1 / signalSFreq) + " and 1 s", NeuroLoopGainController.DefaultErrorMessageId);
                }
                else
                {
                    double inputDoubleValue = doubleValue;
                    //Effective output sampling rate should be an integer number (ej. 2 Hz is ok, 2.1 Hz will be rounded to 2 Hz)
                    doubleValue = MathEx.RoundNearest(1 / doubleValue);
                    Range.EnsureRange(doubleValue, 1, signalSFreq);
                    if (!MathEx.SameValue(inputDoubleValue, (1 / doubleValue)))
                    {
                        textBox.AppendText(Environment.NewLine + "Warning, input SmoothTime will be approximated to " + string.Format("{0}", 1 / doubleValue) + " because the application cannot handle user's innitial value " + string.Format("{0}", doubleValue));
                        ErrorLogger.WriteLog("Warning, input SmoothTime will be approximated to " + string.Format("{0}", 1 / doubleValue) + " because the application cannot handle user's innitial value " + string.Format("{0}", doubleValue));
                    }
                }
            }

            // Calculate Fcompute/IIR_UnderSampler
            if (!NeuroLoopGainController.AppController.ApplicationError.Signaled)
            {
                // Calculate low and high value for IIRunderSampler
                int iirUnderSamplerLo = (int)Math.Truncate(0.99 * signalSFreq / fcomputeMax) + 1;
                int iirUnderSamplerHi = (int)Math.Truncate(signalSFreq / fcomputeMin);
                if (!(iirUnderSamplerLo <= iirUnderSamplerHi))
                {
                    NeuroLoopGainController.AppController.ApplicationError.Add("Unable to find a valid computation frequency. " +
                                                                               "F0 and/or Fc too large, or LP too small", NeuroLoopGainController.DefaultErrorMessageId);
                }

                // IIRUnderSampler == 0 => we want to compute it automatically
                if (_configuration.IIRUnderSampler == 0)
                {
                    // Calculate FcomputeDesired

                    /* Theoretically the next value for FcomputeDesired is ok,
                     * but due to aliasing of alpha and sigma frequencies for
                     * small values of FcomputeDesired it is better to choose
                     * a value around 50 to 60 Hz.
                     *
                     * FcomputeDesired:=4.1*Max(F0,Fc);
                     */
                    const double fcomputeDesired = 56;
                    // Find IIUnderSampler where Fcompute is closest to FcomputeDesired
                    double fcompute = -1;
                    for (int i = iirUnderSamplerLo; i <= iirUnderSamplerHi; i++)
                    {
                        double d = signalSFreq / i;
                        if ((!MathEx.SameValue(fcompute, -1)) &&
                            (Math.Abs(fcomputeDesired - d) >= Math.Abs(fcomputeDesired - fcompute)))
                        {
                            continue;
                        }
                        _configuration.IIRUnderSampler = i;
                        fcompute = d;
                    }
                }
            }

            if (!IsValidFileName(textBoxOutputFileName.Text))
            {
                textBoxOutputFileName.Focus();
                NeuroLoopGainController.AppController.ApplicationError.Add("Output path or filename is not valid", NeuroLoopGainController.DefaultErrorMessageId);
            }

            return(!NeuroLoopGainController.AppController.ApplicationError.Signaled);
        }
Exemplo n.º 19
0
 public override bool Miller(float n, int iteration) => MathEx.Miller((int)n, iteration);
Exemplo n.º 20
0
        private static string GetMedoidImageString(StatisticalResultCsv item)
        {
            try
            {
                //string labelFile = $"{Config.WorkingFolder}\\{item.Method}\\{item.Dataset}\\individuals\\{item.File}";
                DegradomeType dt;
                Enum.TryParse(item.Degredome, out dt);
                FeatureType ft = FeatureTypeExtension.FromString(item.DataType);

                double[,] X = Ezfx.Csv.Ex.CsvMatrix.Read($"{Config.WorkingFolder}\\cs_datasets\\{item.Dataset}.csv");


                //if (item.Method.ToUpper() == "KMEDOIDS")
                //{
                //    medoidIndices = labels.Distinct().OrderBy(c => c).ToArray();
                //}
                //else if (ft != FeatureType.Reactivity)
                //{
                //    medoidIndices = CsMetrics.GetMedoidsByDistanceMatrix(labelFile, item.Dataset).Select(c => c.Index).ToArray();
                //}
                //else
                //{
                //    medoidIndices = CsMetrics.GetMedoids(labelFile, item.Dataset).Select(c => c.Index).ToArray();
                //}

                //medoidIndices = ft == FeatureType.Reactivity ? CsMetrics.GetMedoids(labelFile, item.Dataset).Select(c => c.Index).ToArray() : FileExtension.Readlabels(labelFile).Distinct().ToArray();

                string medoidImageString = "#### Structure\r\n\r\nFor clustering algorithms using reactivity, the structure is for reference only .\r\n\r\n";
                int    index             = 0;

                string[] centerBitmapFiles = new string[medoidIndices.Length];
                string[] annotation        = new string[medoidIndices.Length];
                for (int i = 0; i < medoidIndices.Length; i++)
                {
                    centerBitmapFiles[i] =
                        $"{Config.CsStrucFolder}\\plot\\{dt}_{item.Length}_{medoidIndices[i]}.png";
                    annotation[i] = $"Medoid {i}";
                }

                if (ft == FeatureType.RnaDistance)
                {
                    double[,] medoidDistanceMatrix = Clustering.Metrics.GetSubDistanceMatrix(X, medoidIndices);
                    medoidImageString += Rmd.StartRBlock("distance_matrx");
                    medoidImageString += Rmd.PrintMatrix(medoidDistanceMatrix);
                    medoidImageString += Rmd.EndRBlock();
                    if (medoidIndices.Length == 3)
                    {
                        string guid = Guid.NewGuid().ToString().Replace("-", "_");
                        string file = $"{Config.WorkingFolder}\\reports\\figure\\{guid}.png";
                        ImageHelper.DistanceTriangle(file, centerBitmapFiles, MathEx.DistanceMatrixToTriangle(medoidDistanceMatrix));
                        medoidImageString += Rmd.InsertImage(file, "distance");
                    }
                }

                int[][] samples = Metrics.Sample(labels, 20);



                for (int i = 0; i < medoidIndices.Length; i++)
                {
                    medoidImageString += $"##### Centre of Cluster {index} (Data Point {medoidIndices[i]})\r\n\r\n";
                    medoidImageString += Rmd.InsertImage(centerBitmapFiles[i], "Cleavage site structure");
                    if (ft == FeatureType.RnaDistance)
                    {
                        string thumbFile = GetFilename();
                        medoidImageString += $"Other structures of the this group:\r\n\r\n";
                        medoidImageString += $"![Cleavage site structure]({thumbFile.Replace("\\", "\\\\")})\r\n\r\n";
                        GenerateGroupThumbnails(thumbFile, item, samples[i]);
                        //star
                        if (medoidIndices.Length == 3)
                        {
                            medoidImageString += $"examine the first of the above:\r\n\r\n";
                            string starFile = GetFilename();
                            medoidImageString += $"![Cleavage site structure]({starFile.Replace("\\", "\\\\")})\r\n\r\n";
                            int first = samples[i][0];
                            ImageHelper.Star(starFile,
                                             $"{Config.WorkingFolder}\\cs_rna_struct\\plot\\{item.Degredome}_{item.Length}_{first + 1}.png",
                                             $"CS {first + 1}",
                                             centerBitmapFiles, annotation,
                                             new float[] { (float)X[first, medoidIndices[0]], (float)X[first, medoidIndices[1]], (float)X[first, medoidIndices[2]] }
                                             );
                        }
                    }
                    index++;
                }
                return(medoidImageString);
            }
            catch (NotImplementedException)
            {
                //throw;
                return(string.Empty);
            }
        }
Exemplo n.º 21
0
 public override bool Miller(BigDecimal n, int iteration) => MathEx.Miller((BigInteger)n, iteration);
Exemplo n.º 22
0
        static double[,] Equalize(BlockMap blocks, byte[,] image, int[, ,] histogram, bool[,] blockMask)
        {
            const double maxScaling = 3.99;
            const double minScaling = 0.25;

            const double rangeMin  = -1;
            const double rangeMax  = 1;
            const double rangeSize = rangeMax - rangeMin;

            const double widthMax = rangeSize / 256 * maxScaling;
            const double widthMin = rangeSize / 256 * minScaling;

            var limitedMin   = new double[256];
            var limitedMax   = new double[256];
            var toFloatTable = new double[256];

            for (int i = 0; i < 256; ++i)
            {
                limitedMin[i]   = Math.Max(i * widthMin + rangeMin, rangeMax - (255 - i) * widthMax);
                limitedMax[i]   = Math.Min(i * widthMax + rangeMin, rangeMax - (255 - i) * widthMin);
                toFloatTable[i] = i / 255;
            }

            var cornerMapping = new double[blocks.CornerCount.Y, blocks.CornerCount.X, 256];

            foreach (var corner in blocks.AllCorners)
            {
                if (corner.Get(blockMask, false) ||
                    new Point(corner.X - 1, corner.Y).Get(blockMask, false) ||
                    new Point(corner.X, corner.Y - 1).Get(blockMask, false) ||
                    new Point(corner.X - 1, corner.Y - 1).Get(blockMask, false))
                {
                    int area = 0;
                    for (int i = 0; i < 256; ++i)
                    {
                        area += histogram[corner.Y, corner.X, i];
                    }
                    double widthWeigth = rangeSize / area;

                    double top = rangeMin;
                    for (int i = 0; i < 256; ++i)
                    {
                        double width     = histogram[corner.Y, corner.X, i] * widthWeigth;
                        double equalized = top + toFloatTable[i] * width;
                        top += width;

                        double limited = equalized;
                        if (limited < limitedMin[i])
                        {
                            limited = limitedMin[i];
                        }
                        if (limited > limitedMax[i])
                        {
                            limited = limitedMax[i];
                        }
                        cornerMapping[corner.Y, corner.X, i] = limited;
                    }
                }
            }

            var result = new double[blocks.PixelCount.Y, blocks.PixelCount.X];

            foreach (var block in blocks.AllBlocks)
            {
                if (block.Get(blockMask))
                {
                    var area = blocks.BlockAreas[block];
                    for (int y = area.Bottom; y < area.Top; ++y)
                    {
                        for (int x = area.Left; x < area.Right; ++x)
                        {
                            byte pixel = image[y, x];

                            double bottomLeft  = cornerMapping[block.Y, block.X, pixel];
                            double bottomRight = cornerMapping[block.Y, block.X + 1, pixel];
                            double topLeft     = cornerMapping[block.Y + 1, block.X, pixel];
                            double topRight    = cornerMapping[block.Y + 1, block.X + 1, pixel];

                            var fraction = area.GetFraction(new Point(x, y));
                            result[y, x] = MathEx.Interpolate(topLeft, topRight, bottomLeft, bottomRight, fraction);
                        }
                    }
                }
            }
            return(result);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Triggered when the rotate snap increment value changes.
 /// </summary>
 /// <param name="value">Value that determines in what increments to perform rotate snapping.</param>
 private void OnRotateSnapValueChanged(float value)
 {
     Handles.RotateSnapAmount = (Degree)MathEx.Clamp(value, 0.01f, 360.0f);
     editorSettingsHash       = EditorSettings.Hash;
 }
Exemplo n.º 24
0
 private static bool IsRoofAbove(IRoof roof, Vector3 position)
 {
     return(roof.GetLevel() > position.y && MathEx.IsPointInPolygon(position, roof.GetPolygon()));
 }
Exemplo n.º 25
0
 static EdgeShape()
 {
     for (var y = 0; y < PolarCacheRadius; ++y)
     {
         for (var x = 0; x < PolarCacheRadius; ++x)
         {
             PolarDistance[y, x] = Convert.ToInt16(Math.Round(Math.Sqrt(MathEx.Sq(x) + MathEx.Sq(y))));
             if (y > 0 || x > 0)
             {
                 PolarAngle[y, x] = Angle.AtanB(new Point(x, y));
             }
             else
             {
                 PolarAngle[y, x] = 0;
             }
         }
     }
 }
Exemplo n.º 26
0
        // Defensive

        protected virtual bool ShouldSlowTime(out Vector3 position)
        {
            position = Vector3.Zero;

            var skill = Skills.Wizard.SlowTime;

            if (!skill.CanCast())
            {
                return(false);
            }

            var myPosition      = ZetaDia.Me.Position;
            var clusterPosition = TargetUtil.GetBestClusterPoint(0f, 50f);
            var bubbles         = SpellHistory.FindSpells(skill.SNOPower, 12).ToList();
            var bubblePositions = new List <Vector3>(bubbles.Select(b => b.TargetPosition));
            var isDefensiveRune = Runes.Wizard.PointOfNoReturn.IsActive || Runes.Wizard.StretchTime.IsActive || Runes.Wizard.Exhaustion.IsActive;

            bool IsBubbleAtPosition(Vector3 pos) => bubblePositions
            .Any(b => b.Distance(pos) <= 14f &&
                 pos.Distance(myPosition) < SlowTimeRange);

            // On Self
            if (TargetUtil.ClusterExists(15f, 60f, 8) && isDefensiveRune && !IsBubbleAtPosition(myPosition))
            {
                position = MathEx.GetPointAt(myPosition, 10f, Player.Rotation);
                return(true);
            }

            // On Elites
            if (CurrentTarget.IsElite && CurrentTarget.Distance < SlowTimeRange && !IsBubbleAtPosition(CurrentTarget.Position))
            {
                position = CurrentTarget.Position;
                return(true);
            }

            // On Clusters
            if (TargetUtil.ClusterExists(50f, 5) && clusterPosition.Distance(myPosition) < SlowTimeRange && !IsBubbleAtPosition(clusterPosition))
            {
                position = clusterPosition;
                return(true);
            }

            // Delseres Magnum Opus Set
            if (Sets.DelseresMagnumOpus.IsEquipped)
            {
                var isLargeCluster = Core.Clusters.LargeCluster.Exists && Core.Clusters.LargeCluster.Position.Distance(myPosition) < SlowTimeRange;
                if (isLargeCluster && !IsBubbleAtPosition(Core.Clusters.LargeCluster.Position))
                {
                    position = Core.Clusters.LargeCluster.Position;
                    return(true);
                }

                var isAnyCluster = Core.Clusters.BestCluster.Exists && Core.Clusters.BestCluster.Position.Distance(myPosition) < SlowTimeRange;
                if (isAnyCluster && !IsBubbleAtPosition(Core.Clusters.BestCluster.Position))
                {
                    position = Core.Clusters.BestCluster.Position;
                    return(true);
                }

                if (!IsBubbleAtPosition(myPosition))
                {
                    position = MathEx.GetPointAt(myPosition, 10f, Player.Rotation);
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 27
0
 internal static double ToRadians(double angle) => MathEx.ToRadians(angle);
Exemplo n.º 28
0
        public override void UpdateWeight()
        {
            base.UpdateWeight();

            if (CentreDistance >= 4f && FunkyGame.Targeting.Cache.Environment.NearbyAvoidances.Count > 0)
            {
                Vector3 TestPosition = Position;
                if (ObjectCache.Obstacles.IsPositionWithinAvoidanceArea(TestPosition))
                {
                    Weight = 1;
                }
                else if (ObjectCache.Obstacles.TestVectorAgainstAvoidanceZones(TestPosition))                 //intersecting avoidances..
                {
                    Weight = 1;
                }
            }

            if (Weight != 1)
            {
                float   centreDistance = CentreDistance;
                Vector3 BotPosition    = FunkyGame.Hero.Position;
                switch (targetType.Value)
                {
                case TargetType.Shrine:
                    Weight = 14500d - (Math.Floor(centreDistance) * 170d);
                    // Very close shrines get a weight increase
                    if (centreDistance <= 20f)
                    {
                        Weight += 1000d;
                    }

                    // health pool
                    if (base.IsHealthWell)
                    {
                        if (FunkyGame.Hero.dCurrentHealthPct > 0.75d)
                        {
                            Weight = 0;
                        }
                        else
                        {
                            //Give weight based upon current health percent.
                            Weight += 1000d / (FunkyGame.Hero.dCurrentHealthPct);
                        }
                    }
                    else if (this.Gizmotype.Value == GizmoType.PoolOfReflection)
                    {
                        Weight += 1000;
                    }

                    if (Weight > 0)
                    {
                        // Was already a target and is still viable, give it some free extra weight, to help stop flip-flopping between two targets
                        if (Equals(FunkyGame.Targeting.Cache.LastCachedTarget))
                        {
                            Weight += 600;
                        }
                        // Are we prioritizing close-range stuff atm? If so limit it at a value 3k lower than monster close-range priority
                        if (FunkyGame.Hero.bIsRooted)
                        {
                            Weight = 18500d - (Math.Floor(centreDistance) * 200);
                        }
                        // If there's a monster in the path-line to the item, reduce the weight by 25%
                        if (!Equipment.NoMonsterCollision && ObjectCache.Obstacles.Monsters.Any(cp => cp.TestIntersection(this, BotPosition)))
                        {
                            Weight *= 0.75;
                        }
                    }
                    break;

                case TargetType.Interactable:
                case TargetType.Door:
                    Weight = 15000d - (Math.Floor(centreDistance) * 170d);
                    if (centreDistance <= 30f && RadiusDistance <= 5f)
                    {
                        Weight += 8000d;
                    }
                    // Was already a target and is still viable, give it some free extra weight, to help stop flip-flopping between two targets
                    if (Equals(FunkyGame.Targeting.Cache.LastCachedTarget) && centreDistance <= 25f)
                    {
                        Weight += 1000;
                    }

                    //Check doors against intersection of current target unit when using ranged skill
                    if (targetType.Value == TargetType.Door)
                    {
                        if (FunkyGame.Targeting.Cache.CurrentTarget != null &&
                            FunkyGame.Targeting.Cache.CurrentUnitTarget != null &&
                            FunkyGame.Hero.Class.LastUsedAbility.IsRanged)
                        {
                            if (MathEx.IntersectsPath(Position, CollisionRadius.Value, FunkyGame.Hero.Position,
                                                      FunkyGame.Targeting.Cache.CurrentTarget.Position))
                            {
                                Helpers.Logger.DBLog.InfoFormat("[Funky] Door Blocking current target when using ranged skill!");
                                Weight += 10000;
                            }
                        }
                    }


                    break;

                case TargetType.Container:
                    Weight = 11000d - (Math.Floor(centreDistance) * 190d);
                    if (centreDistance <= 12f)
                    {
                        Weight += 600d;
                    }
                    // Was already a target and is still viable, give it some free extra weight, to help stop flip-flopping between two targets
                    if (Equals(FunkyGame.Targeting.Cache.LastCachedTarget) && centreDistance <= 25f)
                    {
                        Weight += 400;
                    }
                    // If there's a monster in the path-line to the item, reduce the weight by 50%
                    if (!Equipment.NoMonsterCollision && ObjectCache.Obstacles.Monsters.Any(cp => cp.TestIntersection(this, BotPosition)))
                    {
                        Weight *= 0.5;
                    }
                    if (IsResplendantChest)
                    {
                        Weight += 1500;
                    }

                    break;

                case TargetType.CursedShrine:
                case TargetType.CursedChest:
                    Weight = 11000d - (Math.Floor(centreDistance) * 190d);
                    break;
                }

                //Special Custom Weight Check (From Profile Tags)
                if (FunkyGame.Game.ObjectCustomWeights.ContainsKey(SNOID))
                {
                    Weight += FunkyGame.Game.ObjectCustomWeights[SNOID];
                }
            }
            else
            {
                Weight         = 0;
                BlacklistLoops = 15;
            }
        }
Exemplo n.º 29
0
 protected void SwapBlks()
 {
     MathEx.Swap(ref _blk, ref _blk2);
     MathEx.Swap(ref _blkLen, ref _blk2Len);
     MathEx.Swap(ref _blkStart, ref _blk2Start);
 }
Exemplo n.º 30
0
        public override void UpdateWeight()
        {
            base.UpdateWeight();

            Vector3 TestPosition = Position;

            //Use modified Test Position for Gold/Globe
            if (Bot.Character.Data.PickupRadius > 0f && ObjectCache.CheckTargetTypeFlag(targetType.Value, TargetType.Globe | TargetType.Gold))
            {
                TestPosition = MathEx.CalculatePointFrom(Bot.Character.Data.Position, Position, Math.Max(0f, CentreDistance - Bot.Character.Data.PickupRadius));
            }

            if (Bot.Character.Data.Position.Distance(TestPosition) >= 2f)
            {
                //If we are already ignored this recently.. lets just assume its still being ignored!
                if (DateTime.Now.Subtract(LastAvoidanceIgnored).TotalMilliseconds < 1000 && Bot.Targeting.Cache.Environment.NearbyAvoidances.Count > 0)
                {
                    Weight = 1;
                }
                else
                {
                    //Test if this object is within any avoidances
                    if (ObjectCache.Obstacles.IsPositionWithinAvoidanceArea(TestPosition))
                    {
                        Weight = 1;
                    }

                    //Test intersection of avoidances
                    else if (ObjectCache.Obstacles.TestVectorAgainstAvoidanceZones(TestPosition))
                    {
                        Weight = 1;
                    }
                }
            }

            if (Weight != 1)
            {
                Vector3 BotPosition    = Bot.Character.Data.Position;
                float   centreDistance = BotPosition.Distance(TestPosition);

                switch (targetType.Value)
                {
                case TargetType.Item:
                    //this.Weight=(Bot.ItemRange*275)-(Math.Floor(centreDistance)*1000d);
                    Weight = 15000d - (Math.Floor(centreDistance) * 190d);
                    // Point-blank items get a weight increase
                    if (centreDistance <= 12f)
                    {
                        Weight += 600d;
                    }
                    // Was already a target and is still viable, give it some free extra weight, to help stop flip-flopping between two targets
                    if (this == Bot.Targeting.Cache.LastCachedTarget)
                    {
                        Weight += 600;
                    }
                    // Give yellows more weight
                    if (Itemquality.Value >= ItemQuality.Rare4)
                    {
                        Weight += 6000d;
                    }
                    // Give legendaries more weight
                    if (Itemquality.Value >= ItemQuality.Legendary)
                    {
                        Weight += 10000d;

                        double rangelimitRatio = CentreDistance / LootRadius;
                        if (rangelimitRatio > 0.5d && PriorityCounter == 0)
                        {
                            //prioritize!
                            Weight         += 25000d;
                            PrioritizedDate = DateTime.Now;
                            PriorityCounter = 5;
                        }
                    }
                    // Are we prioritizing close-range stuff atm? If so limit it at a value 3k lower than monster close-range priority
                    if (Bot.Character.Data.bIsRooted)
                    {
                        Weight = 18000 - (Math.Floor(centreDistance) * 200);
                    }
                    // If there's a monster in the path-line to the item, reduce the weight
                    if (ObjectCache.Obstacles.Monsters.Any(cp => cp.PointInside(Position)))
                    {
                        Weight *= 0.75;
                    }
                    //Finally check if we should reduce the weight when more then 2 monsters are nearby..
                    //if (Bot.Targeting.Cache.Environment.SurroundingUnits>2&&
                    //     //But Only when we are low in health..
                    //        (Bot.Character_.Data.dCurrentHealthPct<0.25||
                    //     //Or we havn't changed targets after 2.5 secs
                    //        DateTime.Now.Subtract(Bot.Targeting.Cache.LastChangeOfTarget).TotalSeconds>2.5))
                    //     this.Weight*=0.10;

                    //Test if there are nearby units that will trigger kite action..
                    if (Bot.Character.Data.ShouldFlee)
                    {
                        if (ObjectCache.Objects.OfType <CacheUnit>().Any(m => m.ShouldFlee && m.IsPositionWithinRange(Position, Bot.Settings.Fleeing.FleeMaxMonsterDistance)))
                        {
                            Weight = 1;
                        }
                    }

                    //Did we have a target last time? and if so was it a goblin?
                    if (Bot.Targeting.Cache.LastCachedTarget.RAGUID != -1 && Bot.Settings.Targeting.GoblinPriority > 1)
                    {
                        if (Bot.Targeting.Cache.LastCachedTarget.IsTreasureGoblin)
                        {
                            Weight = 0;
                        }
                    }
                    break;

                case TargetType.Gold:
                    if (GoldAmount > 0)
                    {
                        Weight = 11000d - (Math.Floor(centreDistance) * 200d);
                    }
                    // Was already a target and is still viable, give it some free extra weight, to help stop flip-flopping between two targets
                    if (this == Bot.Targeting.Cache.LastCachedTarget)
                    {
                        Weight += 600;
                    }
                    // Are we prioritizing close-range stuff atm? If so limit it at a value 3k lower than monster close-range priority
                    if (Bot.Character.Data.bIsRooted)
                    {
                        Weight = 18000 - (Math.Floor(centreDistance) * 200);
                    }
                    // If there's a monster in the path-line to the item, reduce the weight by 25%
                    if (ObjectCache.Obstacles.Monsters.Any(cp => cp.TestIntersection(this, BotPosition)))
                    {
                        Weight *= 0.75;
                    }
                    //Did we have a target last time? and if so was it a goblin?
                    if (Bot.Targeting.Cache.LastCachedTarget.RAGUID != -1)
                    {
                        if (Bot.Targeting.Cache.LastCachedTarget.IsTreasureGoblin)
                        {
                            Weight = 0;
                        }
                    }
                    break;

                case TargetType.Globe:
                case TargetType.PowerGlobe:
                    if (targetType.Equals(TargetType.Globe) && Bot.Character.Data.dCurrentHealthPct > Bot.Settings.Combat.GlobeHealthPercent)
                    {
                        Weight = 0;
                    }
                    else
                    {
                        // Ok we have globes enabled, and our health is low...!
                        Weight = 17000d - (Math.Floor(centreDistance) * 90d);

                        // Point-blank items get a weight increase
                        if (centreDistance <= 15f)
                        {
                            Weight += 3000d;
                        }

                        // Close items get a weight increase
                        if (centreDistance <= 60f)
                        {
                            Weight += 1500d;
                        }

                        if (targetType == TargetType.PowerGlobe)
                        {
                            Weight += 5000d;
                        }

                        // Was already a target and is still viable, give it some free extra weight, to help stop flip-flopping between two targets
                        if (this == Bot.Targeting.Cache.LastCachedTarget && centreDistance <= 25f)
                        {
                            Weight += 400;
                        }

                        // If there's a monster in the path-line to the item, reduce the weight
                        if (ObjectCache.Obstacles.Monsters.Any(cp => cp.TestIntersection(BotPosition, TestPosition)))
                        {
                            Weight *= 0.25f;
                        }

                        // Calculate a spot reaching a little bit further out from the globe, to help globe-movements
                        //if (this.Weight>0)
                        //    this.Position=MathEx.CalculatePointFrom(this.Position, Bot.Character_.Data.Position, this.CentreDistance+3f);
                    }
                    break;
                }
            }
            else
            {
                LastAvoidanceIgnored = DateTime.Now;

                //Skipped Due To Avoidances -- Gold and Globes, we blacklist them for a bit so we don't rerun the tests over and over!
                if (targetType.Value != TargetType.Item)
                {
                    Weight         = 0;             //Zero will ignore the object completely! (Target)
                    BlacklistLoops = 10;
                }
            }
        }
 public ExifURational(ExifTag tag, MathEx.UFraction32 value)
     : base(tag)
 {
     mValue = value;
 }
        private bool TryGoOcculus(out TrinityPower power)
        {
            power = null;

            if (!Core.Rift.IsGreaterRift)
            {
                return(false);
            }

            if (!IsInCombat)
            {
                return(false);
            }

            if (_g_isAvoiding)
            {
                return(false);
            }

            if (!CanTeleport && IsStuck)
            {
                return(false);
            }

            Vector3 occulusPos = Vector3.Zero;

            if (!GetOculusPosition(out occulusPos, 58f, Player.Position))
            {
                return(false);
            }

            if (occulusPos == Vector3.Zero)
            {
                return(false);
            }

            float distance = occulusPos.Distance(Player.Position);

            if (Core.Rift.IsGaurdianSpawned && CurrentTarget != null && CurrentTarget.IsBoss && occulusPos.Distance(CurrentTarget.Position) < 15f)
            {
                return(false);
            }


            if (Core.Avoidance.InCriticalAvoidance(occulusPos) && !Core.Buffs.HasInvulnerableShrine)
            {
                return(false);
            }

            TrinityActor target = ClosestTarget2(occulusPos, CastDistance);

            if (!IsValidTarget(target))
            {
                if (DebugMode)
                {
                    Core.Logger.Warn($"神目周围{CastDistance}码内没有可以攻击的怪物,放弃踩神目");
                }
                return(false);
            }

            if (distance < 9f)
            {
                if (DebugMode)
                {
                    Core.Logger.Warn($"已经在神目中,无需移动");
                }
                return(false);
            }
            else if (CanTeleport)
            {
                if (DebugMode)
                {
                    Core.Logger.Warn($"飞向神目");
                }
                power = Teleport(occulusPos);
            }
            else if (distance < 25f && Core.Buffs.HasBuff(74499))
            {
                Vector3 closePos = MathEx.CalculatePointFrom(occulusPos, Player.Position, 10f);
                if (Core.Grids.CanRayWalk(Player.Position, closePos))
                {
                    if (DebugMode)
                    {
                        Core.Logger.Warn($"向神目步行移动,距离我{distance}");
                    }
                    power = Walk(occulusPos);
                }
                else
                {
                    if (DebugMode)
                    {
                        Core.Logger.Warn($"神目不能直线到达,放弃");
                    }
                    return(false);
                }
            }
            else
            {
                if (DebugMode)
                {
                    Core.Logger.Warn($"神目距离{distance}不合适,放弃");
                }

                return(false);
            }

            return(power != null);
        }
 /// <summary>
 /// Converts the given array of signed rationals to an array of bytes.
 /// Numbers are converted from the platform byte-order to the given byte-order.
 /// </summary>
 public static byte[] GetBytes(MathEx.Fraction32[] value, ByteOrder tobyteorder)
 {
     byte[] data = new byte[8 * value.Length];
     for (int i = 0; i < value.Length; i++)
     {
         byte[] num = GetBytes(value[i].Numerator, ByteOrder.System, tobyteorder);
         byte[] den = GetBytes(value[i].Denominator, ByteOrder.System, tobyteorder);
         Array.Copy(num, 0, data, i * 8, 4);
         Array.Copy(den, 0, data, i * 8 + 4, 4);
     }
     return data;
 }
Exemplo n.º 34
0
        public object ScanIndexer(Benchmarker b)
        {
            int Cycles = Math.Max(MathEx.MulDiv(StdIterations, 100, _count), 1);
            int r      = b.ActiveBenchmarkName.IndexOf("repeatedly");

            if (r > -1)
            {
                b.ActiveBenchmarkName = b.ActiveBenchmarkName.Left(r) + Cycles + "x";
            }

            _graphConfiguration[b.ActiveBenchmarkName] = plotModel => {
                AddStandardAxes(plotModel, string.Format("Milliseconds to perform {0:n0} iterations", StdIterations * 100));
            };

            b.Run("List", b_ =>
            {
                var list = MakeList(new List <long>(), b_);
                long sum = 0;
                for (int c = 0; c < Cycles; c++)
                {
                    sum = 0;
                    for (int i = 0; i < list.Count; i++)
                    {
                        sum += list[i];
                    }
                }
                return("Sum: " + sum);
            });
            b.Run("InternalList", TestOther, b_ =>
            {
                var list = MakeList(InternalList <long> .Empty, b_);
                long sum = 0;
                for (int c = 0; c < Cycles; c++)
                {
                    sum = 0;
                    for (int i = 0; i < list.Count; i++)
                    {
                        sum += list[i];
                    }
                }
                return("Sum: " + sum);
            });
            b.Run("DList", TestDLists, b_ =>
            {
                var list = MakeList(new DList <long>(), b_);
                long sum = 0;
                for (int c = 0; c < Cycles; c++)
                {
                    sum = 0;
                    for (int i = 0; i < list.Count; i++)
                    {
                        sum += list[i];
                    }
                }
                return("Sum: " + sum);
            });
            b.Run("\u200BInternalDList", TestDLists, b_ =>
            {
                b_.PauseTimer();
                var list = InternalDList <long> .Empty;
                for (int i = 0; i < _count; i++)
                {
                    list.Add(i);
                }
                _r = new Random(_seed);
                b_.ResumeTimer();

                long sum = 0;
                for (int c = 0; c < Cycles; c++)
                {
                    sum = 0;
                    for (int i = 0; i < list.Count; i++)
                    {
                        sum += list[i];
                    }
                }
                return("Sum: " + sum);
            });
            b.Run("AList", TestALists, b_ =>
            {
                var list = MakeList(new AList <long>(), b_);
                long sum = 0;
                for (int c = 0; c < Cycles; c++)
                {
                    sum = 0;
                    for (int i = 0; i < list.Count; i++)
                    {
                        sum += list[i];
                    }
                }
                return("Sum: " + sum);
            });
            return(Benchmarker.DiscardResult);
        }