Esempio n. 1
0
    private Unity.Mathematics.float2 RandomInRing(float innerRadius, float outerRadius)
    {
        var pos          = Utils.GetRotatedPosition(Vector2.right * Random.Range(innerRadius, outerRadius), Random.Range(0, 360f));
        var randomInRing = new Unity.Mathematics.float2(pos.x, pos.y);

        return(randomInRing);
    }
Esempio n. 2
0
    public static float2[] GeneratePoints(int count, ref Random random, Func <float2, float> density = null, Func <float2, float> envelope = null, Action <string> progressCallback = null)
    {
        if (density == null)
        {
            density = v => .5f;
        }
        if (envelope == null)
        {
            envelope = v => 1;
        }
        var inputSamples = new float2[count * 8];
        var sample       = 0;
        var accumulator  = 0f;

        while (sample < inputSamples.Length)
        {
            var v = random.NextFloat2();
            accumulator += pow(saturate(density(v)), 2f) * saturate(envelope(v));
            if (accumulator > .5f)
            {
                accumulator            = 0;
                inputSamples[sample++] = v;
                progressCallback?.Invoke($"Generating Samples: {sample} / {inputSamples.Length}");
            }
        }
        var outputSamples = new float2[count];

        progressCallback?.Invoke("Eliminating Samples");
        Eliminate(inputSamples, outputSamples, density);
        return(outputSamples);
    }
Esempio n. 3
0
        private static float Dot2(Vector2 a, Vector2 b)
        {
#if MATHEMATICS
            return(dot(a, b));
#else
            return(Vector2.Dot(a, b));
#endif
        }
Esempio n. 4
0
 public void MoveTo(float2 position, bool matchVelocity = true, Action onFinish = null)
 {
     TargetPosition  = () => position;
     TargetVelocity  = () => float2.zero;
     MatchVelocity   = matchVelocity;
     _movementPhase  = MovementPhase.Locomotion;
     Moving          = true;
     _onFinishMoving = onFinish;
 }
Esempio n. 5
0
    // private IEnumerator AnimatePath()
    // {
    //     var pathZones = ActionGameManager.CurrentSector.ExitPath;
    //     LegendPanel.SetActive(false);
    //     PathAnimationButton.gameObject.SetActive(false);
    //
    //     var revealCount = ActionGameManager.CurrentSector.Entrance.Distance[ActionGameManager.CurrentSector.Exit];
    //     Map.StartReveal(
    //         PathAnimationDuration / revealCount * (LinkAnimationDuration / (IconAnimationDuration + LinkAnimationDuration)),
    //         PathAnimationDuration / revealCount * (IconAnimationDuration / (IconAnimationDuration + LinkAnimationDuration)));
    //     MainCamera.enabled = false;
    //     SectorCamera.targetTexture = null;
    //     Canvas.gameObject.SetActive(false);
    //     SectorCamera.gameObject.SetActive(true);
    //
    //     var pathAnimationLerp = 0f;
    //     while (pathAnimationLerp < 1)
    //     {
    //         var currentTargetZone = pathZones[(int) (pathZones.Length * pathAnimationLerp)];
    //         _position = lerp(_position, currentTargetZone.Position, PathAnimationDamping);
    //         pathAnimationLerp += Time.deltaTime / (PathAnimationDuration * PathAnimationDurationPadding);
    //         UpdateCamera();
    //         yield return null;
    //     }
    //
    //     LegendPanel.SetActive(true);
    //     PathAnimationButton.gameObject.SetActive(true);
    // }

    private void OnEnable()
    {
        _init = true;
        SectorCamera.gameObject.SetActive(true);
        _position = GameManager.Zone.GalaxyZone.Position;
        _viewSize = .25f;

        Map.StartReveal(LinkAnimationDuration, IconAnimationDuration);
        Map.MarkPlayerLocation(GameManager.CurrentEntity.Zone.GalaxyZone);
    }
Esempio n. 6
0
    public void OnScroll(PointerEventData eventData)
    {
        var mapCenter          = float2((float)Screen.width / 2, (float)Screen.height / 2);
        var oldPointerPosition = _position + ((float2)eventData.position - mapCenter) / Screen.height * _viewSize;

        _viewSize = clamp(_viewSize * (1 - eventData.scrollDelta.y * ZoomSpeed), MinViewSize, MaxViewSize);
        var pointerPosition = _position + ((float2)eventData.position - mapCenter) / Screen.height * _viewSize;

        _position += oldPointerPosition - pointerPosition;
    }
Esempio n. 7
0
 public void MoveDirection(Unity.Mathematics.float2 direction)
 {
     if (push_time_remaining > 0f)
     {
         push_time_remaining = Mathf.Max(0f, push_time_remaining - Time.deltaTime);
         rigid_body.velocity = push_velocity;
     }
     else
     {
         rigid_body.velocity = direction * move_speed;
     }
 }
Esempio n. 8
0
    //MCTS Agent
    public static long GetHashCode(ref GameState gs, int playerId)
    {
        var enemyPosition = gs.players[1].position;

        Unity.Mathematics.float2 ennemyLookDirection = gs.players[playerId].lookDirection;

        //distance entre player et ennemyPlayer
        Unity.Mathematics.float2 VectorBetweenPlayerAndEnnemy =
            new Unity.Mathematics.float2(gs.players[1].position.x - gs.players[0].position.x,
                                         gs.players[1].position.y - gs.players[0].position.y);

        var angle = Unity.Mathematics.math.acos(
            Unity.Mathematics.math.clamp(
                Unity.Mathematics.math.dot(gs.players[0].lookDirection, VectorBetweenPlayerAndEnnemy), -1f, 1f)) * 57.29578f;


        return((long)angle);
    }
Esempio n. 9
0
    // Create children that fill a single orbit, equally spaced
    // https://en.wikipedia.org/wiki/Klemperer_rosette
    public void ExpandRosette(ref Random random, int vertices)
    {
        //Debug.Log("Expanding Rosette");

        // Rosette children replace the parent, parent orbital node is left empty
        Empty = true;

        // Masses in a rosette alternate, so every sequential pair has the same shared mass
        var sharedMass = Mass / vertices * 2;

        // Proportion of the masses of sequential pairs is random, but only for even vertex counts
        var proportion = vertices % 2 == 0 ? random.NextFloat(.5f, .95f) : .5f;

        // Place children at a fixed distance in the center of the range
        var dist = (ChildDistanceMinimum + ChildDistanceMaximum) / 2;

        // Position of first child
        var p0 = new float2(0, dist);

        // Position of second child
        var p1 = OrbitData.Evaluate(1.0f / vertices) * dist;

        // Maximum child distance is half the distance to the neighbor minus the neighbor's radius
        var p0ChildDist = (distance(p0, p1) * proportion - Settings.PlanetSafetyRadius.Evaluate(sharedMass * (1 - proportion))) * .75f;
        var p1ChildDist = (distance(p0, p1) * (1 - proportion) - Settings.PlanetSafetyRadius.Evaluate(sharedMass * proportion)) * .75f;

        for (int i = 0; i < vertices; i++)
        {
            var child = new GeneratorPlanet
            {
                Settings             = Settings,
                Parent               = this,
                Mass                 = sharedMass * (i % 2 == 0 ? proportion : 1 - proportion), // Masses alternate
                Distance             = dist,
                Phase                = (float)i / vertices,
                ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist)
            };
            child.ChildDistanceMinimum = Settings.PlanetSafetyRadius.Evaluate(child.Mass) * 2;
            //child.Period = Settings..Evaluate(child.Distance);
            Children.Add(child);
        }

        ChildDistanceMinimum = dist + p0ChildDist;
    }
Esempio n. 10
0
    public static float2 Rotate(this float2 v, ItemRotation rotation)
    {
        switch (rotation)
        {
        case ItemRotation.None:
            return(v);

        case ItemRotation.CounterClockwise:
            return(float2(-v.y, v.x));

        case ItemRotation.Reversed:
            return(float2(-v.x, -v.y));

        case ItemRotation.Clockwise:
            return(float2(v.y, -v.x));

        default:
            throw new ArgumentOutOfRangeException(nameof(rotation), rotation, null);
        }
    }
Esempio n. 11
0
    public void Accelerate(float2 targetVelocity, bool noTurn = false)
    {
        var deltaV          = targetVelocity - Ship.Velocity;
        var deltaVMag       = length(deltaV);
        var deltaVDirection = normalize(deltaV);

        // If Delta V is above the threshold, direct the ship towards the delta and use only main thrusters
        if (!noTurn && deltaVMag > FORWARD_DELTA_THRESHOLD)
        {
            Ship.LookDirection     = float3(deltaVDirection.x, 0, deltaVDirection.y);
            Ship.MovementDirection = float2(0, pow(dot(Ship.Direction, deltaVDirection), 2));
        }
        // If Delta V is low, direct the ship towards the target and use all thrusters
        else if (deltaVMag > THRUST_DELTA_THRESHOLD)
        {
            var right = Ship.Direction.Rotate(ItemRotation.Clockwise);
            Ship.MovementDirection = float2(dot(right, deltaVDirection), dot(Ship.Direction, deltaVDirection));
        }
        else
        {
            Ship.MovementDirection = float2.zero;
        }
    }
Esempio n. 12
0
 public static float2 floor(float2 a)
 {
     return(new float2(floor(a.x), floor(a.y)));
 }
Esempio n. 13
0
 public static float2 asin(float2 a)
 {
     return(new float2(asin(a.x), asin(a.y)));
 }
Esempio n. 14
0
 public static float2 sin(float2 a)
 {
     return(new float2(sin(a.x), sin(a.y)));
 }
Esempio n. 15
0
 public static float2 acos(float2 a)
 {
     return(new float2(acos(a.x), acos(a.y)));
 }
Esempio n. 16
0
 [MethodImpl((MethodImplOptions)0x100)] // agressive inline
 public static bool2 notEqual(float2 x, float2 y)
 {
     return(x != y);
 }
Esempio n. 17
0
    // static float ResourceValue(ref Random random, ZoneGenerationSettings settings, SimpleCommodityData resource, float density)
    // {
    //  return random.NextPowerDistribution(resource.Minimum, resource.Maximum, resource.Exponent,
    //      1 / lerp(settings.ResourceDensityMinimum, settings.ResourceDensityMaximum, density));
    // }

    public static GeneratorPlanet[] GenerateEntities(ZoneGenerationSettings settings, ref Random random, float mass, float radius, float2 fixedPosition)
    {
        var root = new GeneratorPlanet
        {
            FixedPosition        = fixedPosition,
            Settings             = settings,
            Mass                 = mass,
            ChildDistanceMaximum = radius * .75f,
            ChildDistanceMinimum = settings.PlanetSafetyRadius.Evaluate(mass)
        };

        // There is some chance of generating a rosette or binary system
        // Probabilities which are fixed for the entire galaxy are in GlobalData, contained in the GameContext
        var rosette = random.NextFloat() < settings.RosetteProbability;

        if (rosette)
        {
            // Create a rosette with a number of vertices between 2 and 9 inclusive
            root.ExpandRosette(ref random, (int)(random.NextFloat(1, 5) + random.NextFloat(1, 5)));

            // Create a small number of less massive "captured" planets orbiting past the rosette
            root.ExpandSolar(
                ref random,
                count: (int)(random.NextFloat(1, 3) * random.NextFloat(1, 2)),
                massMulMin: .6f,
                massMulMax: .8f,
                distMulMin: 1.25f,
                distMulMax: 1.75f,
                jupiterJump: 1,
                massFraction: .1f);

            var averageChildMass = root.Children.Sum(p => p.Mass) / root.Children.Count;
            foreach (var p in root.Children.Where(c => c.Mass > settings.GasGiantMass))
            {
                var m = p.Mass / averageChildMass;
                // Give each child in the rosette its own mini solar system
                p.ExpandSolar(
                    ref random,
                    count: (int)(random.NextFloat(1, 3 * m) + random.NextFloat(1, 3 * m)),
                    massMulMin: 0.75f,
                    massMulMax: 2.5f,
                    distMulMin: 1 + m * .25f,
                    distMulMax: 1.05f + m * .5f,
                    jupiterJump: random.NextFloat() * random.NextFloat() * 10 + 1,
                    massFraction: .5f
                    );
            }
        }
        else
        {
            // Create a regular old boring solar system
            root.ExpandSolar(
                ref random,
                count: random.NextInt(5, 15),
                massMulMin: 0.75f,
                massMulMax: 2.5f,
                distMulMin: 1.1f,
                distMulMax: 1.25f,
                jupiterJump: random.NextFloat() * random.NextFloat() * 10 + 1,
                massFraction: .25f
                );
        }

        var alreadyExpanded = new List <GeneratorPlanet>();
        var binaries        = new List <GeneratorPlanet>();

        for (int i = 0; i < settings.SatellitePasses; i++)
        {
            // Get all children that are above the satellite creation mass floor and not rosette members
            var satelliteCandidates = rosette
                                ? root.AllPlanets().Where(p =>
                                                          p != root &&
                                                          p.Parent != root &&
                                                          p.Mass > settings.SatelliteCreationMassFloor &&
                                                          !alreadyExpanded.Contains(p))
                                : root.AllPlanets().Where(p =>
                                                          p != root &&
                                                          p.Mass > settings.SatelliteCreationMassFloor &&
                                                          !alreadyExpanded.Contains(p));

            foreach (var planet in satelliteCandidates)
            {
                // There's a chance of generating satellites for each qualified planet
                if (random.NextFloat() < settings.SatelliteCreationProbability)
                {
                    // Sometimes the satellite is so massive that it forms a binary system (like Earth!)
                    if (random.NextFloat() < settings.BinaryCreationProbability)
                    {
                        planet.ExpandRosette(ref random, 2);
                        binaries.AddRange(planet.Children);
                    }
                    // Otherwise, terrestrial planets get a couple satellites while gas giants get many
                    else
                    {
                        planet.ExpandSolar(
                            ref random,
                            count: planet.Mass < settings.GasGiantMass ? random.NextInt(1, 3) : random.NextInt(2, 6),
                            massMulMin: .75f,
                            massMulMax: 1.5f,
                            distMulMin: 1.05f,
                            distMulMax: 1.25f,
                            jupiterJump: 1,
                            massFraction: .15f);                             // Planetary satellites are not nearly as massive as planets themselves
                    }
                    alreadyExpanded.Add(planet);
                }
            }
        }

        // Get all children that are below the belt creation mass floor and not rosette members, also exclude binaries
        var beltCandidates = rosette
                        ? root.AllPlanets().Where(p => p != root && p.Parent != root && p.Mass < settings.BeltMassCeiling && !binaries.Contains(p) && p.Children.Count == 0)
                        : root.AllPlanets().Where(p => p != root && p.Mass < settings.BeltMassCeiling && !binaries.Contains(p) && p.Children.Count == 0);

        foreach (var planet in beltCandidates.Reverse())
        {
            if (random.NextFloat() < settings.BeltProbability && !planet.Parent.Children.Any(p => p.Belt))
            {
                planet.Belt = true;
            }
        }

        var totalMass = root.AllPlanets().Sum(p => p.Mass);
        var rootMass  = root.Mass;

        foreach (var planet in root.AllPlanets())
        {
            planet.Mass = (planet.Mass / totalMass) * rootMass;
        }

        return(root.AllPlanets().ToArray());
    }
Esempio n. 18
0
 public Circle(float2 center, float radius)
 {
     Center = center;
     Radius = radius;
 }
Esempio n. 19
0
 [MethodImpl((MethodImplOptions)0x100)] // agressive inline
 public static float dot(float2 pt1, float2 pt2)
 {
     return(pt1.x * pt2.x + pt1.y * pt2.y);
 }
Esempio n. 20
0
 [MethodImpl((MethodImplOptions)0x100)] // agressive inline
 public static float2 saturate(float2 x)
 {
     return(clamp(x, new float2(0.0F), new float2(1.0F)));
 }
Esempio n. 21
0
 [MethodImpl((MethodImplOptions)0x100)] // agressive inline
 public static float2 min(float2 a, float2 b)
 {
     return(new float2(min(a.x, b.x), min(a.y, b.y)));
 }
Esempio n. 22
0
 [MethodImpl((MethodImplOptions)0x100)] // agressive inline
 public static float2 clamp(float2 x, float2 a, float2 b)
 {
     return(max(a, min(b, x)));
 }
Esempio n. 23
0
 [MethodImpl((MethodImplOptions)0x100)] // agressive inline
 public static float2 mad(float2 a, float2 b, float2 c)
 {
     return(a * b + c);
 }
Esempio n. 24
0
        /// <summary>
        /// Recursive splitting procedure
        /// </summary>
        /// <param name="parent">This is where root node goes</param>
        /// <param name="depth"></param>
        ///
        void SplitNode(KDNode parent)
        {
            // center of bounding box
            KDBounds parentBounds     = parent.bounds;
            var      parentBoundsSize = parentBounds.size;

            // Find axis where bounds are largest
            int   splitAxis = 0;
            float axisSize  = parentBoundsSize.x;

            if (axisSize < parentBoundsSize.y)
            {
                splitAxis = 1;
                axisSize  = parentBoundsSize.y;
            }

            // Our axis min-max bounds
            float boundsStart = parentBounds.min[splitAxis];
            float boundsEnd   = parentBounds.max[splitAxis];

            // Calculate the spliting coords
            float splitPivot = CalculatePivot(parent.start, parent.end, boundsStart, boundsEnd, splitAxis);

            parent.partitionAxis       = splitAxis;
            parent.partitionCoordinate = splitPivot;

            // 'Spliting' array to two subarrays
            int splittingIndex = Partition(parent.start, parent.end, splitPivot, splitAxis);

            // Negative / Left node
            float2 negMax = parentBounds.max;

            negMax[splitAxis] = splitPivot;

            KDNode negNode = GetKDNode();

            negNode.bounds       = parentBounds;
            negNode.bounds.max   = negMax;
            negNode.start        = parent.start;
            negNode.end          = splittingIndex;
            parent.negativeChild = negNode;

            // Positive / Right node
            float2 posMin = parentBounds.min;

            posMin[splitAxis] = splitPivot;

            KDNode posNode = GetKDNode();

            posNode.bounds       = parentBounds;
            posNode.bounds.min   = posMin;
            posNode.start        = splittingIndex;
            posNode.end          = parent.end;
            parent.positiveChild = posNode;

            // check if we are actually splitting it anything
            // this if check enables duplicate coordinates, but makes construction a bit slower
#if KDTREE_DUPLICATES
            if (negNode.Count != 0 && posNode.Count != 0)
            {
            #endif
            // Constraint function deciding if split should be continued
            if (ContinueSplit(negNode))
            {
                SplitNode(negNode);
            }


            if (ContinueSplit(posNode))
            {
                SplitNode(posNode);
            }

#if KDTREE_DUPLICATES
        }
#endif
        }
Esempio n. 25
0
 public static float2 atan(float2 value)
 {
     return(new float2(atan(value.x), atan(value.y)));
 }
Esempio n. 26
0
 public static float2 atan2(float2 pt1, float2 pt2)
 {
     return(new float2(atan2(pt1.x, pt2.x), atan2(pt1.y, pt2.y)));
 }
Esempio n. 27
0
 public float DistanceTo(float2 point) => length(point - Center) - Radius;
Esempio n. 28
0
 public static float2 cos(float2 a)
 {
     return(new float2(cos(a.x), cos(a.y)));
 }
Esempio n. 29
0
 [MethodImpl((MethodImplOptions)0x100)] // agressive inline
 public static float2 abs(float2 a)
 {
     return(max(-a, a));
 }
Esempio n. 30
0
 [MethodImpl((MethodImplOptions)0x100)] // agressive inline
 public static bool2 equal(float2 x, float2 y)
 {
     return(x == y);
 }