protected override Tuple<string[], string[]> GenerateInputOutput() {
      FastRandom rand = new FastRandom();
      List<List<int>> vectors = GetHardcodedTrainingSamples();
      var zeros = GetHardcodedZeros();
      var trainZeros = zeros.SampleRandomWithoutRepetition(rand, 30).ToList();
      var testZeros = zeros.Except<List<int>>(trainZeros, new EnumerableValueEqualityComparer<int>()).ToList();
      var help1 = GetDistinctPermutations(new int[4] { 0, 5, -8, 9 });
      var trainHelp1 = help1.SampleRandomWithoutRepetition(rand, 20).ToList();
      var testHelp1 = help1.Except<List<int>>(trainHelp1, new EnumerableValueEqualityComparer<int>()).ToList();
      var help2 = GetDistinctPermutations(new int[4] { 0, 0, -8, 9 });
      var trainHelp2 = help2.SampleRandomWithoutRepetition(rand, 10).ToList();
      var testHelp2 = help2.Except<List<int>>(trainHelp2, new EnumerableValueEqualityComparer<int>()).ToList();
      var help3 = GetDistinctPermutations(new int[4] { 0, 0, 0, 9 });

      vectors.AddRange(trainZeros);
      vectors.AddRange(trainHelp1);
      vectors.AddRange(trainHelp2);
      vectors.AddRange(help3);

      vectors.AddRange(GetRandomVectors(78, rand).ToList());

      vectors = vectors.Shuffle(rand).ToList();

      vectors.AddRange(testZeros);
      vectors.AddRange(testHelp1);
      vectors.AddRange(testHelp2);
      vectors.AddRange(GetRandomVectors(974, rand).ToList());

      var input = vectors.Select(x => String.Format("[{0}]", String.Join(", ", x))).ToArray();
      var output = vectors.Select(x => x.LastIndexOf(0).ToString()).ToArray();
      return new Tuple<string[], string[]>(input, output);
    }
 public MsgKeepAlive()
     : base()
 {
     FastRandom fastRand = new FastRandom();
     this.Payload = new byte[fastRand.Next(32, 256)];
     fastRand.NextBytes(this.Payload);
 }
        private void InitBoxes(int Seed)
        {
            FastRandom rnd = new FastRandom(Seed);

            for (int i = 0; i < DataSize; i++)
            {
                //set random values in Box B (The output box)
                byte[] TempValues = new byte[BOX_SIZE];
                for (int x = 0; x < BOX_SIZE; x++)
                    TempValues[x] = (byte)x;
                ShuffleValues(TempValues, Seed);

                for (int j = 0; j < BOX_SIZE; j++)
                {
                    BOX_B[i, j] = TempValues[j];
                }

                //Set in Box A where the index of Box B
                for (int j = 0; j < BOX_SIZE; j++)
                {
                    for (int x = 0; x < BOX_SIZE; x++)
                    {
                        if (BOX_B[i, x] == j)
                        {
                            BOX_A[i, j] = (byte)x;
                            break;
                        }
                    }
                }
            }
        }
Exemple #4
0
 public static String RandomDecimalString(FastRandom r)
 {
     int count = r.NextValue(20) + 1;
       StringBuilder sb = new StringBuilder();
       if (r.NextValue(2) == 0) sb.Append('-');
       for (int i = 0; i < count; i++) {
     if (i == 0)
       sb.Append((char)('1' + r.NextValue(9)));
     else
       sb.Append((char)('0' + r.NextValue(10)));
       }
       if (r.NextValue(2) == 0) {
     sb.Append('.');
     count = r.NextValue(20) + 1;
     for (int i = 0; i < count; i++) {
       sb.Append((char)('0' + r.NextValue(10)));
     }
       }
       if (r.NextValue(2) == 0) {
     sb.Append('E');
     count = r.NextValue(20);
     if (count != 0) {
       sb.Append(r.NextValue(2) == 0 ? '+' : '-');
     }
     sb.Append(Convert.ToString(
       (int)count, CultureInfo.InvariantCulture));
       }
       return sb.ToString();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="NeuralColorQuantizer"/> class.
        /// </summary>
        public NeuralColorQuantizer()
        {
            Quality = DefaultQuality;

            random = new FastRandom(0);
            uniqueColors = new ConcurrentDictionary<Int32, Boolean>();
        }
 public MarkovChainSampler()
 {
     this.sampleCache = new Stack<Sample>(100);
     rnd = new FastRandom();
     TotalSamples = 0L;
     samplesInPass = 0;
 }
 /// <summary>
 /// Constructs with the provided world parameter arguments.
 /// </summary>
 public PreyCaptureWorld(int gridSize, int preyInitMoves, double preySpeed, double sensorRange, int maxTimesteps)
 {
     _gridSize = gridSize;
     _preyInitMoves = preyInitMoves;
     _preySpeed = preySpeed;
     _sensorRange = sensorRange;
     _maxTimesteps = maxTimesteps;
     _rng = new FastRandom();
 }
 /// <summary>
 /// Initializes a new instance from an existing one (copy constructor).
 /// </summary>
 /// <param name="original">The original <see cref="FastRandom"/> instance which is used to initialize the new instance.</param>
 /// <param name="cloner">A <see cref="Cloner"/> which is used to track all already cloned objects in order to avoid cycles.</param>
 private FastRandom(FastRandom original, Cloner cloner)
   : base(original, cloner) {
   x = original.x;
   y = original.y;
   z = original.z;
   w = original.w;
   bitBuffer = original.bitBuffer;
   bitMask = original.bitMask;
 }
Exemple #9
0
 public void InitNoise() {
     var RNG = new FastRandom();
     NoiseTable = new float[NoiseDim + 1, NoiseDim + 1, NoiseDim + 1];
     int i, j, k;
     for (i = 0; i < NoiseDim; i++)
         for (j = 0; j < NoiseDim; j++)
             for (k = 0; k < NoiseDim; k++)
                 NoiseTable[i, j, k] = RNG.NextFloat();
 }
        public MarkovChain(MarkovChainNode[] nodes, int stepsPerActivation, FastRandom random)
        {
            _nodes = nodes;
            _stepsPerActivation = stepsPerActivation;
            _random = random;

            _rouletteWheels = new RouletteWheelLayout[nodes.Length];
            for (int i = 0; i < nodes.Length; i++)
                _rouletteWheels[i] = new RouletteWheelLayout(nodes[i].TransitionProbabilities);
        }
 private IEnumerable<List<int>> GetRandomVectors(int n, FastRandom rand) {
   for (int i = 0; i < n; i++) {
     int length = rand.Next(1, 50);
     List<int> cur = new List<int>(length) { 0 };
     for (int j = 0; j < length - 1; j++) {
       cur.Add(rand.Next(-50, 50));
     }
     yield return cur.Shuffle(rand).ToList();
   }
 }
 public PathGenerator(uint seed, GetHeight getHeight)
 {
     m_getHeight = getHeight;
     var fastRandom = new FastRandom(seed);
     m_cellNoise = new CellNoise2D(fastRandom.NextUInt());
     m_sources = new Dictionary<uint, PathGraphNode>();
     m_sinks = new Dictionary<uint, PathGraphNode>();
     m_general = new Dictionary<uint, PathGraphNode>();
     m_paths = new List<PathNodeList>();
 }
        public FiniteAppertureCamera(Point eye, Vector dirt, Vector up, int width, int height, float fov)
        {
            rnd = new FastRandom();
            this.fieldOfView = fov;
            this.Height = height;
            this.Width = width;
            this.Position = eye;
            this.Target = dirt;
            this.Up = up;

            this.Update();
        }
Exemple #14
0
 public void TestCBORObjectDecimal()
 {
     FastRandom rand = new FastRandom();
       for (int i = 0; i <= 28; i++) { // Try a random decimal with a given exponent
     for (int j = 0; j < 8; j++) {
       decimal d = RandomDecimal(rand, i);
       CBORObject obj = CBORObject.FromObject(d);
       TestCommon.AssertRoundTrip(obj);
       Assert.AreEqual(d, obj.AsDecimal());
     }
       }
 }
    //protected override IEnumerable<int> GenerateTraining() {
    //  var x0 = new List<int>() { 1, 2, 3, 4, 5, 100 };
    //  x0.AddRange(ValueGenerator.SampleRandomWithoutRepetition(numbers, 44, rand));
    //  return x0;
    //}

    //protected override IEnumerable<int> GenerateTest() {
    //  return numbers.Except(GenerateTraining());
    //}

    //protected override Tuple<string[], string[]> GenerateInputOutput(IEnumerable<int> x0) {
    //  var input = x0.Select(x => x.ToString()).ToArray();
    //  var output = x0.Select(x => CalcSumOfSquares(x).ToString()).ToArray();
    //  return new Tuple<string[], string[]>(input, output);
    //}

    protected override Tuple<string[], string[]> GenerateInputOutput() {
      FastRandom rand = new FastRandom();
      var x0 = new List<int>() { 1, 2, 3, 4, 5, 100 };
      x0.AddRange(ValueGenerator.SampleRandomWithoutRepetition(numbers, 44, rand));

      x0 = x0.Shuffle(rand).ToList();

      x0.AddRange(numbers.Except(x0));

      var input = x0.Select(x => x.ToString()).ToArray();
      var output = x0.Select(x => CalcSumOfSquares(x).ToString()).ToArray();
      return new Tuple<string[], string[]>(input, output);
    }
Exemple #16
0
 public static String RandomBigIntString(FastRandom r)
 {
     int count = r.NextValue(50) + 1;
       StringBuilder sb = new StringBuilder();
       if (r.NextValue(2) == 0) sb.Append('-');
       for (int i = 0; i < count; i++) {
     if (i == 0)
       sb.Append((char)('1' + r.NextValue(9)));
     else
       sb.Append((char)('0' + r.NextValue(10)));
       }
       return sb.ToString();
 }
Exemple #17
0
        public MazeWallMover (Maze maze, Maze secondMaze, GameState state,
            Func<int, int, bool> containsPortal)
        {
            Maze = maze;
            SecondMaze = secondMaze;
            this.GameState = state;
            rand = new FastRandom(maze.Seed);
            this.containsPortal = containsPortal;

            ValidMessages = new[] { (int) MessageId.Update };

            this.GameState.MessageProxy.RegisterMessageConsumer(this);
            this.GameState.MessageProxy.AddMessageCreator (this);
        }
        public TriangleMeshLight(LightMaterial mt, RayEngineScene scene, TriangleMeshInfo mesh) : base(mt)
        {
            this.scene = scene;
            this.mesh = mesh;
            this.rnd = new FastRandom();

            triangleSampleData = new TriangleSample[this.mesh.TrianglesCount];

            for (int i = mesh.StartTriangle, j = 0; i < mesh.EndTriangle; i++, j++)
            {
                triangleSampleData[j] = new TriangleSample(scene.Triangles[i].AreaV(scene.Vertices), NormalModifier * scene.Triangles[i].ComputeNormal(scene.Vertices));
            }

            triangleSampleData.PartialSort((a, b) => a.Item1.CompareTo(a.Item1), 0, triangleSampleData.Length);

        }
Exemple #19
0
        private void InitGen()
        {
            
            if (GenInit)
                return;

            GenInit = true;

            _Gen1 = new PerlinNoise(_Seed);
            _Gen2 = new PerlinNoise(_Seed + 1);
            _Gen3 = new PerlinNoise(_Seed + 2);
            _Gen4 = new PerlinNoise(_Seed + 3);
            _Gen5 = new PerlinNoise(_Seed + 4);
            _Gen6 = new PerlinNoise(_Seed + 5);
            _FastRandom = new FastRandom(_Seed);
        }
Exemple #20
0
        static void RunTrial(int offset)
        {
            RESULTS_FILE = EXPERIMENTS_DIR + RESULTS_FILE_BASE + offset + ".csv";
            _random = new FastRandom();

            _experiment = new SocialExperiment();
            XmlDocument xmlConfig = new XmlDocument();
            xmlConfig.Load(CONFIG_FILE);
            _experiment.Initialize("SimpleEvolution", xmlConfig.DocumentElement);
            _experiment.NeatGenomeParameters.AddConnectionMutationProbability = 0;
            _experiment.NeatGenomeParameters.AddNodeMutationProbability = 0;
            _experiment.NeatGenomeParameters.DeleteConnectionMutationProbability = 0;
            
            SocialExperiment.CreateNetwork(FEED_FORWARD_NETWORK_FILE, _experiment.InputCount, _experiment.OutputCount);

            // Record the changes at each step
            _experiment.World.Stepped += new social_learning.World.StepEventHandler(World_Stepped);

            // Read in the seed genome from file. This is the prototype for our other population of networks.
            var seed = _experiment.LoadPopulation(XmlReader.Create(FEED_FORWARD_NETWORK_FILE))[0];

            // Create a genome factory with our neat genome parameters object and the appropriate number of input and output neuron genes.
            IGenomeFactory<NeatGenome> genomeFactory = _experiment.CreateGenomeFactory();

            // Create an initial population of randomly generated genomes.
            List<NeatGenome> genomeList = genomeFactory.CreateGenomeList(_experiment.DefaultPopulationSize, 0, seed);

            // Randomize the genomes
            RandomizeGenomes(genomeList);

            // Create genome decoder.
            IGenomeDecoder<NeatGenome, IBlackBox> genomeDecoder = _experiment.CreateGenomeDecoder();

            // Create the evaluator that will handle the simulation
            _evaluator = new ForagingEvaluator<NeatGenome>(genomeDecoder, _experiment.World, AgentTypes.Social)
                {
                    MaxTimeSteps = 200000UL,
                    BackpropEpochsPerExample = 1
                };

            using (TextWriter writer = new StreamWriter(RESULTS_FILE))
                writer.WriteLine("Step,Best,Average");

            // Start the simulation
            _evaluator.Evaluate(genomeList);
        }
Exemple #21
0
    public Problem()
      : base() {
      Parameters.Add(new FixedValueParameter<IntValue>(LawnWidthParameterName, "Width of the lawn.", new IntValue(8)));
      Parameters.Add(new FixedValueParameter<IntValue>(LawnLengthParameterName, "Length of the lawn.", new IntValue(8)));

      var g = new SimpleSymbolicExpressionGrammar();
      g.AddSymbols(new string[] { "Sum", "Prog" }, 2, 2);
      g.AddSymbols(new string[] { "Frog" }, 1, 1);
      g.AddTerminalSymbols(new string[] { "Left", "Forward" });
      // initialize 20 ephemeral random constants in [0..32[
      var fastRand = new FastRandom(314159);
      for (int i = 0; i < 20; i++) {
        g.AddTerminalSymbol(string.Format("{0},{1}", fastRand.Next(0, 32), fastRand.Next(0, 32)));
      }

      Encoding = new SymbolicExpressionTreeEncoding(g, 1000, 17);
    }
        /// <summary>
        /// See <see cref="BaseColorCacheQuantizer.OnGetPaletteToCache"/> for more details.
        /// </summary>
        protected override List<Color> OnGetPaletteToCache(Int32 colorCount)
        {
            // use fast random class
            FastRandom random = new FastRandom(0);

            // NOTE: I've added a little randomization here, as it was performing terribly otherwise.
            // sorts out the list by a pixel presence, takes top N slots, and calculates
            // the average color from them, thus our new palette.
            IEnumerable<Color> colors = colorMap.
                 OrderBy(entry => random.Next(colorMap.Count)).
                 OrderByDescending(entry => entry.Value.PixelCount).
                 Take(colorCount).
                 Select(entry => entry.Value.GetAverage());

            palette.Clear();
            palette.AddRange(colors);
            return palette;
        }
Exemple #23
0
        /// <summary>
        ///     Averages out the number of partitions possible given the evolved maze dimensions.
        /// </summary>
        /// <param name="mazeHeight">The height of the maze.</param>
        /// <param name="mazeWidth">The width of the maze.</param>
        /// <param name="numSamples">The number of sample mazes to attempt partitioning out to get a representative average.</param>
        /// <returns>The average number of partitions supportable within the given maze dimensions.</returns>
        public static int DetermineMaxPartitions(int mazeHeight, int mazeWidth, int numSamples)
        {
            int[] maxMazeResolutions = new int[numSamples];
            FastRandom rng = new FastRandom();

            // Fully partition maze space for the specified number of samples
            for (int curSample = 0; curSample < numSamples; curSample++)
            {
                Queue<MazeStructureRoom> mazeRoomQueue = new Queue<MazeStructureRoom>();
                int[,] mazeSegments = new int[mazeHeight, mazeWidth];
                int partitionCount = 0;

                // Queue up the first "room" (which will encompass the entirety of the maze grid)
                mazeRoomQueue.Enqueue(new MazeStructureRoom(0, 0, mazeWidth, mazeHeight));

                // Iterate until there are no more available sub fields in the queue
                while (mazeRoomQueue.Count > 0)
                {
                    // Dequeue a room and run division on it
                    Tuple<MazeStructureRoom, MazeStructureRoom> subRooms = mazeRoomQueue.Dequeue()
                        .DivideRoom(mazeSegments, rng.NextDoubleNonZero(),
                            rng.NextDoubleNonZero(),
                            rng.NextDoubleNonZero() > 0.5);

                    if (subRooms != null)
                    {
                        // Increment the count of partitions
                        partitionCount++;

                        // Get the two resulting sub rooms and enqueue both of them
                        mazeRoomQueue.Enqueue(subRooms.Item1);
                        mazeRoomQueue.Enqueue(subRooms.Item2);
                    }
                }

                // Record the total number of maze partitions
                maxMazeResolutions[curSample] = partitionCount;
            }

            // Return the minimum number of partitions associated with a fully partitioned maze
            return (int) maxMazeResolutions.Average(partition => partition);
        }
Exemple #24
0
    /**
     * @param seed
     */
    public PerlinNoise(long seed) {
        FastRandom rand = new FastRandom(seed);
        _noisePermutations = new int[512];
        _noiseTable = new int[256];

        for (int i = 0; i < 256; i++)
            _noiseTable[i] = i;

        for (int i = 0; i < 256; i++) {
            int j = rand.randomInt() % 256;

            j = (j < 0) ? -j : j;

            int swap = _noiseTable[i];
            _noiseTable[i] = _noiseTable[j];
            _noiseTable[j] = swap;
        }

        for (int i = 0; i < 256; i++)
            _noisePermutations[i] = _noisePermutations[i + 256] = _noiseTable[i];
    }
Exemple #25
0
            public Sample GetNextSample(FastRandom rnd)
            {
                curX++;
                if (curX >= Width)
                {
                    curY++;
                    curX = 0;
                    if (curY >= Height)
                    {
                        curY = 0;
                        CurrentPass++;
                    }
                }
                var data = (new float[sampleDepth]).Select(item => rnd.NextFloat()).ToArray();

                return new Sample()
                    {
                        ImageX = curX,
                        ImageY = Height - curY - 1,
                        Data = data
                    };
            }
Exemple #26
0
 //[Test]
 public void GenerateDecimalTests()
 {
     FastRandom r = new FastRandom();
       for(int i=0;i<5000;i++){
     CBORObject o1=CBORTest.RandomNumber(r);
     var df=o1.AsExtendedDecimal();
     try {
       decimal s=Decimal.Parse(df.ToPlainString(),CultureInfo.InvariantCulture);
       try {
     var df2=df.RoundToBinaryPrecision(
       new PrecisionContext(96,Rounding.HalfEven,0,28,true));
     if(df2.Exponent<(BigInteger)(-28) ||
        df2.Exponent>BigInteger.Zero){
       Console.WriteLine(df2);
     }
     Assert.AreEqual(s.ToString(CultureInfo.InvariantCulture),df2.ToPlainString());
       } catch(Exception){
     Console.WriteLine(
       "Assert.AreEqual(\""+s.ToString(CultureInfo.InvariantCulture)+
       "\",ExtendedDecimal.FromString(\""+df.ToString()+"\")"+
       ".RoundToBinaryPrecision(new PrecisionContext(96,Rounding.HalfEven,0,28,false)).ToPlainString());"
      );
     throw;
       }
     } catch(OverflowException){
       try {
     Assert.AreEqual(null,df.RoundToBinaryPrecision(
       new PrecisionContext(96,Rounding.HalfEven,0,28,false)));
       } catch(Exception){
     Console.WriteLine(
       "Assert.AreEqual(null,ExtendedDecimal.FromString(\""+df.ToString()+"\")"+
       ".RoundToBinaryPrecision(new PrecisionContext(96,Rounding.HalfEven,0,28,false)));"
      );
     throw;
       }
     }
       }
 }
Exemple #27
0
        static void Main(string[] args)
        {
            _random = new FastRandom();

            _experiment = new SocialExperiment();
            XmlDocument xmlConfig = new XmlDocument();
            xmlConfig.Load(CONFIG_FILE);
            _experiment.Initialize("SimpleEvolution", xmlConfig.DocumentElement);
            _experiment.NeatGenomeParameters.AddConnectionMutationProbability = 0;
            _experiment.NeatGenomeParameters.AddNodeMutationProbability = 0;
            _experiment.NeatGenomeParameters.DeleteConnectionMutationProbability = 0;

            SocialExperiment.CreateNetwork(FEED_FORWARD_NETWORK_FILE, _experiment.InputCount, 20, _experiment.OutputCount);

            // Record the changes at each step
            _experiment.World.Stepped += new social_learning.World.StepEventHandler(World_Stepped);

            // Read in the teacher genome from file.
            var agentGenome = _experiment.LoadPopulation(XmlReader.Create(FEED_FORWARD_NETWORK_FILE));

            // Create genome decoder.
            IGenomeDecoder<NeatGenome, IBlackBox> genomeDecoder = _experiment.CreateGenomeDecoder();

            // Create the evaluator that will handle the simulation
            _evaluator = new ForagingEvaluator<NeatGenome>(genomeDecoder, _experiment.World, AgentTypes.QLearning)
            {
                MaxTimeSteps = 50000000UL,
                BackpropEpochsPerExample = 1
            };

            using (TextWriter writer = new StreamWriter(RESULTS_FILE))
                writer.WriteLine("Step,Score");

            // Start the simulation
            _evaluator.Evaluate(agentGenome);
        }
 /// <summary>
 /// Genetic mutation for auxiliary argument data.
 /// </summary>
 public void MutateAuxArgs(double[] auxArgs, FastRandom rng, ZigguratGaussianSampler gaussianSampler, double connectionWeightRange)
 {
     throw new SharpNeatException("MutateAuxArgs() called on activation function that does not use auxiliary arguments.");
 }
 private double GetRandomModifier()
 {
     return(1.0 - (FastRandom.NextDouble(-0.5, 0.5) * SCAN_INTRUSION_RANDOM_FACTOR * (1.0 - _module.ScanAccuracy.Clamp())));
 }
 public FreeRoamingPathFinder(IZone zone)
 {
     _zone      = zone;
     _direction = FastRandom.NextDouble();
 }
 /// <summary>
 /// For activation functions that accept auxiliary arguments; generates random initial values for aux arguments for newly
 /// added nodes (from an 'add neuron' mutation).
 /// </summary>
 public double[] GetRandomAuxArgs(FastRandom rng, double connectionWeightRange)
 {
     throw new SharpNeatException("GetRandomAuxArgs() called on activation function that does not use auxiliary arguments.");
 }
        private IToolImpact BlockHit(IDynamicEntity owner)
        {
            var impact = new BlockToolImpact {
                SrcBlueprintId = BluePrintId,
                Position       = owner.EntityState.PickedBlockPosition
            };

            var cursor = LandscapeManager.GetCursor(owner.EntityState.PickedBlockPosition);

            if (cursor == null)
            {
                //Impossible to find chunk, chunk not existing, event dropped
                impact.Message = "Block not existing, event dropped";
                impact.Dropped = true;
                return(impact);
            }
            cursor.OwnerDynamicId = owner.DynamicId;

            if (cursor.PeekProfile().Indestructible)
            {
                impact.Message = "Indestrutible cube, cannot be removed !";
                return(impact);
            }

            DamageTag damage;

            var cube = cursor.Read(out damage);

            if (cube != WorldConfiguration.CubeId.Air)
            {
                impact.CubeId = cube;
                var profile  = cursor.PeekProfile();
                var hardness = profile.Hardness;

                if (damage == null)
                {
                    damage = new DamageTag {
                        Strength      = (int)hardness,
                        TotalStrength = (int)hardness
                    };
                }

                var toolBlockDamage = Damage;

                if (SpecialDamages != null)
                {
                    var index = SpecialDamages.FindIndex(cd => cd.CubeId == cube);

                    if (index != -1)
                    {
                        toolBlockDamage = SpecialDamages[index].Damage;
                    }
                }

                damage.Strength -= toolBlockDamage;

                if (toolBlockDamage > 0 && SoundEngine != null)
                {
                    if (profile.HitSounds.Count > 0)
                    {
                        var random = new Random();
                        var sound  = profile.HitSounds[random.Next(0, profile.HitSounds.Count)];
                        SoundEngine.StartPlay3D(sound, owner.EntityState.PickedBlockPosition + new Vector3(0.5f));
                    }
                }

                if (damage.Strength <= 0)
                {
                    var chunk = LandscapeManager.GetChunkFromBlock(owner.EntityState.PickedBlockPosition);
                    if (chunk == null)
                    {
                        //Impossible to find chunk, chunk not existing, event dropped
                        impact.Message = "Chunk is not existing, event dropped";
                        impact.Dropped = true;
                        return(impact);
                    }
                    chunk.Entities.RemoveAll <BlockLinkedItem>(e => e.Linked && e.LinkedCube == owner.EntityState.PickedBlockPosition, owner.DynamicId);
                    cursor.Write(WorldConfiguration.CubeId.Air);

                    #region TreeSoul remove logic
                    foreach (var treeSoul in EntityFactory.LandscapeManager.AroundEntities(owner.EntityState.PickedBlockPosition, 16).OfType <TreeSoul>())
                    {
                        var treeBp = EntityFactory.Config.TreeBluePrintsDico[treeSoul.TreeTypeId];

                        if (cube != treeBp.FoliageBlock && cube != treeBp.TrunkBlock)
                        {
                            continue;
                        }

                        var treeLSystem = new TreeLSystem();

                        var treeBlocks = treeLSystem.Generate(treeSoul.TreeRndSeed, (Vector3I)treeSoul.Position, treeBp);

                        // did we remove the block of the tree?
                        if (treeBlocks.Exists(b => b.WorldPosition == owner.EntityState.PickedBlockPosition))
                        {
                            treeSoul.IsDamaged = true;

                            // count removed trunk blocks
                            var totalTrunks = treeBlocks.Count(b => b.BlockId == treeBp.TrunkBlock);

                            var existsTrunks = treeBlocks.Count(b =>
                            {
                                if (b.BlockId == treeBp.TrunkBlock)
                                {
                                    cursor.GlobalPosition = b.WorldPosition;
                                    return(cursor.Read() == treeBp.TrunkBlock);
                                }
                                return(false);
                            });

                            if (existsTrunks < totalTrunks / 2)
                            {
                                treeSoul.IsDying = true;
                            }
                        }
                    }
                    #endregion

                    if (SoundEngine != null && EntityFactory.Config.ResourceTake != null)
                    {
                        SoundEngine.StartPlay3D(EntityFactory.Config.ResourceTake, owner.EntityState.PickedBlockPosition + new Vector3(0.5f));
                    }

                    var charEntity = owner as CharacterEntity;
                    if (charEntity == null)
                    {
                        impact.Message = "Charater entity is expected";
                        return(impact);
                    }

                    var putItems = new List <KeyValuePair <IItem, int> >();
                    putItems.Add(new KeyValuePair <IItem, int>((IItem)EntityFactory.CreateFromBluePrint(cube), 1));

                    if (profile.Transformations != null)
                    {
                        var random = new FastRandom(owner.EntityState.PickedEntityPosition.GetHashCode() ^ owner.EntityState.Entropy);
                        foreach (var itemTransformation in profile.Transformations)
                        {
                            if (random.NextDouble() < itemTransformation.TransformChance)
                            {
                                // don't give the block
                                putItems.Clear();
                                foreach (var slot in itemTransformation.GeneratedItems)
                                {
                                    putItems.Add(new KeyValuePair <IItem, int>((Item)EntityFactory.CreateFromBluePrint(slot.BlueprintId), slot.Count));
                                }
                                break;
                            }
                        }
                    }

                    // in case of infinite resources we will not add more than 1 block entity
                    var existingSlot = charEntity.FindSlot(s => s.Item.BluePrintId == cube);

                    if (!EntityFactory.Config.IsInfiniteResources || existingSlot == null)
                    {
                        if (!charEntity.Inventory.PutMany(putItems))
                        {
                            impact.Message = "Can't put the item(s) to inventory";
                        }
                    }

                    impact.CubeId = WorldConfiguration.CubeId.Air;
                }
                else if (damage.Strength >= hardness)
                {
                    cursor.Write(cube);
                }
                else
                {
                    cursor.Write(cube, damage);
                }

                impact.Success = true;
                return(impact);
            }

            impact.Message = "Cannot hit air block";
            return(impact);
        }
Exemple #33
0
 public IBuilder <LootItem> GetLootItemBuilder()
 {
     return(LootItemBuilder.Create(Definition)
            .SetQuantity(FastRandom.NextInt(Quantity))
            .SetRepackaged(Packed));
 }
        public Point FindNextRoamingPosition(RoamingPresence presence)
        {
            var minSlope     = presence.Flocks.GetMembers().Min(m => m.Slope);
            var maxHomeRange = presence.Flocks.Max(f => f.HomeRange);
            var range        = new IntRange((int)(maxHomeRange * 1.1), (int)(maxHomeRange * 1.5));

            var queue     = new PriorityQueue <Node>(500);
            var startNode = new Node(presence.CurrentRoamingPosition);

            queue.Enqueue(startNode);

            var closed = new HashSet <Point> {
                presence.CurrentRoamingPosition
            };

            if (FastRandom.NextDouble() < 0.3)
            {
                _direction += FastRandom.NextDouble(0, 0.25) - 0.25;
                MathHelper.NormalizeDirection(ref _direction);
            }

            var farPosition = startNode.location.ToPosition().OffsetInDirection(_direction, FastRandom.NextDouble(range.Min, range.Max));

//            _zone.CreateAlignedDebugBeam(BeamType.red_20sec,farPosition);

            Node current;

            while (queue.TryDequeue(out current))
            {
                var d = startNode.location.Distance(current.location);
                if (d > range.Min)
                {
                    _direction = startNode.location.DirectionTo(current.location);
//                    _zone.CreateAlignedDebugBeam(BeamType.green_20sec,current.location.ToPosition());
                    return(current.location);
                }

                foreach (var np in current.location.GetNeighbours())
                {
                    if (closed.Contains(np))
                    {
                        continue;
                    }

                    closed.Add(np);

                    if (!_zone.IsWalkableForNpc(np, minSlope))
                    {
                        continue;
                    }

                    if (np.Distance(startNode.location) >= range.Max)
                    {
                        continue;
                    }

//                    _zone.CreateAlignedDebugBeam(BeamType.orange_20sec,np.ToPosition());

                    queue.Enqueue(new Node(np, Heuristic.Manhattan.Calculate(np.X, np.Y, (int)farPosition.X, (int)farPosition.Y)));
                }
            }

            _direction = FastRandom.NextDouble();
            return(presence.CurrentRoamingPosition);
        }
        public void UnHealPlant()
        {
            var amount = FastRandom.NextInt(3, 5);

            health = (byte)(health - amount).Clamp(0, 255);
        }
Exemple #36
0
 public EndTimeObjectPatternGenerator(FastRandom random, HitObject hitObject, ManiaBeatmap beatmap, IBeatmap originalBeatmap)
     : base(random, hitObject, beatmap, new Pattern(), originalBeatmap)
 {
     endTime = (HitObject as IHasEndTime)?.EndTime ?? 0;
 }
Exemple #37
0
        private Boolean[,] GoGenerate(FastRandom r, int width, int height)
        {
            int x = 1;
            int y = 1;


            var map = new Boolean[width, height];


            List <int> stackjex = new List <int>(10000);
            List <int> stackjey = new List <int>(10000);

            int pointertje = 0;

            stackjex.Add(x);
            stackjey.Add(y);
            pointertje++;

            map[x, y] = true;
            //pixelChangedCallback.Invoke(x, y, currentStep, totSteps);

            MazePoint[] targets = new MazePoint[4];

            //form.drawPixel(x, y, brushThisUses);
            while (pointertje > 0)
            {
                x = stackjex[pointertje - 1];
                y = stackjey[pointertje - 1];

                int targetCount = 0;
                if (isValid(x - 2, y, map, width, height))
                {
                    targets[targetCount].X = x - 2;
                    targets[targetCount].Y = y;
                    targetCount++;
                }
                if (isValid(x + 2, y, map, width, height))
                {
                    targets[targetCount].X = x + 2;
                    targets[targetCount].Y = y;
                    targetCount++;
                }
                if (isValid(x, y - 2, map, width, height))
                {
                    targets[targetCount].X = x;
                    targets[targetCount].Y = y - 2;
                    targetCount++;
                }
                if (isValid(x, y + 2, map, width, height))
                {
                    targets[targetCount].X = x;
                    targets[targetCount].Y = y + 2;
                    targetCount++;
                }

                //Thread.Sleep(1000);

                if (targetCount > 0)
                {
                    var target = targets[r.Next(targetCount)];
                    if (pointertje == stackjex.Count)
                    {
                        stackjex.Add(target.X);
                        stackjey.Add(target.Y);
                    }
                    else
                    {
                        stackjex[pointertje] = target.X;
                        stackjey[pointertje] = target.Y;
                    }
                    pointertje++;

                    map[target.X, target.Y] = true;

                    if (target.X < x)
                    {
                        map[x - 1, y] = true;
                        //pixelChangedCallback.Invoke(x - 1, y, currentStep, totSteps);
                        //form.drawPixel(x - 1, y, brushThisUses);
                    }
                    else if (target.X > x)
                    {
                        map[x + 1, y] = true;
                        //pixelChangedCallback.Invoke(x + 1, y, currentStep, totSteps);
                        //form.drawPixel(x + 1, y, brushThisUses);
                    }
                    else if (target.Y < y)
                    {
                        map[x, y - 1] = true;
                        //pixelChangedCallback.Invoke(x, y - 1, currentStep, totSteps);
                        //form.drawPixel(x, y - 1, brushThisUses);
                    }
                    else if (target.Y > y)
                    {
                        map[x, y + 1] = true;
                        //pixelChangedCallback.Invoke(x, y + 1, currentStep, totSteps);
                        //form.drawPixel(x, y + 1, brushThisUses);
                    }
                    //pixelChangedCallback.Invoke(target.X, target.Y, currentStep, totSteps);
                    //form.drawPixel(target.X, target.Y, brushThisUses);
                }
                else
                {
                    pointertje--;
                }
            }

            return(map);
        }
Exemple #38
0
 public Particle(FastRandom rnd)
 {
     Deviation0 = (float)rnd.NextDouble() * 2f - 1f;
     //Deviation1 = (float)rnd.NextDouble() * 2f - 1f;
     //TextureIndex = (ushort)rnd.Next(4);
 }
 public GlobalGenerator(uint seed)
 {
     _random     = new FastRandom(seed);
     _sysRand    = new System.Random((int)seed);
     _heightMap0 = new SimplexNoise2D(_random.NextUInt());
 }
        public HitObjectPatternGenerator(FastRandom random, HitObject hitObject, ManiaBeatmap beatmap, Pattern previousPattern, double previousTime, Vector2 previousPosition, double density,
                                         PatternType lastStair, IBeatmap originalBeatmap)
            : base(random, hitObject, beatmap, previousPattern, originalBeatmap)
        {
            StairType = lastStair;

            TimingControlPoint timingPoint = beatmap.ControlPointInfo.TimingPointAt(hitObject.StartTime);
            EffectControlPoint effectPoint = beatmap.ControlPointInfo.EffectPointAt(hitObject.StartTime);

            var positionData = hitObject as IHasPosition;

            float  positionSeparation = ((positionData?.Position ?? Vector2.Zero) - previousPosition).Length;
            double timeSeparation     = hitObject.StartTime - previousTime;

            if (timeSeparation <= 80)
            {
                // More than 187 BPM
                convertType |= PatternType.ForceNotStack | PatternType.KeepSingle;
            }
            else if (timeSeparation <= 95)
            {
                // More than 157 BPM
                convertType |= PatternType.ForceNotStack | PatternType.KeepSingle | lastStair;
            }
            else if (timeSeparation <= 105)
            {
                // More than 140 BPM
                convertType |= PatternType.ForceNotStack | PatternType.LowProbability;
            }
            else if (timeSeparation <= 125)
            {
                // More than 120 BPM
                convertType |= PatternType.ForceNotStack;
            }
            else if (timeSeparation <= 135 && positionSeparation < 20)
            {
                // More than 111 BPM stream
                convertType |= PatternType.Cycle | PatternType.KeepSingle;
            }
            else if (timeSeparation <= 150 && positionSeparation < 20)
            {
                // More than 100 BPM stream
                convertType |= PatternType.ForceStack | PatternType.LowProbability;
            }
            else if (positionSeparation < 20 && density >= timingPoint.BeatLength / 2.5)
            {
                // Low density stream
                convertType |= PatternType.Reverse | PatternType.LowProbability;
            }
            else if (density < timingPoint.BeatLength / 2.5 || effectPoint.KiaiMode)
            {
                // High density
            }
            else
            {
                convertType |= PatternType.LowProbability;
            }

            if (!convertType.HasFlag(PatternType.KeepSingle))
            {
                if (HitObject.Samples.Any(s => s.Name == SampleInfo.HIT_FINISH) && TotalColumns != 8)
                {
                    convertType |= PatternType.Mirror;
                }
                else if (HitObject.Samples.Any(s => s.Name == SampleInfo.HIT_CLAP))
                {
                    convertType |= PatternType.Gathered;
                }
            }
        }
Exemple #41
0
 public void Initialize()
 {
     _rng = new FastRandom(0xBADC0DE); // Well, we can't use Environment.TickCount, so...
 }
Exemple #42
0
 private IEnumerable <IEnumerable <double> > GetVecotrsOfVariableLenght(int n, FastRandom rand)
 {
     for (int i = 0; i < n; i++)
     {
         yield return(ValueGenerator.GenerateUniformDistributedValues(rand.Next(1, 50 + 1), -1000.0, 1000.0, rand));
     }
 }
 /// <summary>
 /// Genetic mutation for auxiliary argument data.
 /// </summary>
 public void MutateAuxArgs(double[] auxArgs, FastRandom rng, ZigguratGaussianSampler gaussianSampler, double connectionWeightRange)
 {
     throw new SharpNeatException("MutateAuxArgs() called on activation function that does not use auxiliary arguments.");
 }
Exemple #44
0
        public override void SetSpawnPosition (Vector3 playerSpawn, PhysicsComponent ownPhysics, object map, FastRandom rand)
        {
            Maze.Maze maze = map as Maze.Maze;
            if (maze != null)
            {
                bool gotit = false;

                while (!gotit)
                {
                    int pos = rand.Next (0, maze.graph.Nodes.Count);
                    Vector3 spawn_pos;
                    float distance;
                    for (int i = pos; i < maze.graph.Nodes.Count; i++)
                    {
                        spawn_pos = maze.graph.Nodes[i].Data.WorldPosition;
                        Vector3.Distance(ref playerSpawn, ref spawn_pos, out distance);
                        if (maze.graph.Nodes[i].Data.MazeCellType == MazeCellType.Ground && distance > 50 &&
                            !maze.graph.Nodes[i].Data.IsExit)
                        {
                            gotit = true;
                            ownPhysics.RigidBody.Position = new JVector (maze.graph.Nodes[i].Data.WorldPosition.X, height,
                                maze.graph.Nodes[i].Data.WorldPosition.Z);
                            break;
                        }
                    }
                }

                if (!gotit)
                {
                    Logger.Log.AddLogEntry (LogLevel.Severe, "GhostAI", "Failed to generate spawn position!");
                }

                fallback = JVector.Transform (JVector.Backward, JMatrix.CreateFromAxisAngle (JVector.Up,
                    (float) rand.NextDouble() * 2 * MathHelper.Pi));
                direction = fallback;

                Spawned = true;
            }
        }
 internal LootContainerBuilder()
 {
     _containerType = LootContainerType.LootOnly;
     _pinCode       = FastRandom.NextInt(1, 9999);
     _enterBeamType = BeamType.undefined;
 }
Exemple #46
0
        //ennek mindenkepp vegig kell futnia
        private void HandlePlayerDead(IZone zone, Unit killer)
        {
            using (var scope = Db.CreateTransaction())
            {
                EnlistTransaction();
                try
                {
                    killer = zone.ToPlayerOrGetOwnerPlayer(killer) ?? killer;

                    SaveCombatLog(zone, killer);

                    var character = Character;

                    var dockingBase = character.GetHomeBaseOrCurrentBase();
                    dockingBase.DockIn(character, NormalUndockDelay, ZoneExitType.Died);

                    PlayerDeathLogger.Log.Write(zone, this, killer);

                    //pay out insurance if needed
                    var wasInsured = InsuranceHelper.CheckInsuranceOnDeath(Eid, Definition);

                    if (!Session.AccessLevel.IsAdminOrGm())
                    {
                        var robotInventory = GetContainer();
                        Debug.Assert(robotInventory != null);

                        var lootItems = new List <LootItem>();

                        // minden fittelt modul
                        foreach (var module in Modules.Where(m => LootHelper.Roll()))
                        {
                            lootItems.Add(LootItemBuilder.Create(module).AsDamaged().Build());

                            var activeModule = module as ActiveModule;
                            var ammo         = activeModule?.GetAmmo();
                            if (ammo != null)
                            {
                                if (LootHelper.Roll())
                                {
                                    lootItems.Add(LootItemBuilder.Create(ammo).Build());
                                }
                            }

                            // szedjuk le a robotrol
                            module.Parent = robotInventory.Eid; //in case the container is full

                            //toroljuk is le, nem kell ez sehova mar
                            Repository.Delete(module);
                        }

                        foreach (var item in robotInventory.GetItems(true).Where(i => i is VolumeWrapperContainer))
                        {
                            //Transport assignments
                            var wrapper = item as VolumeWrapperContainer;
                            if (wrapper == null)
                            {
                                continue;
                            }

                            lootItems.AddRange(wrapper.GetLootItems());
                            wrapper.SetAllowDelete();
                            Repository.Delete(wrapper);
                        }

                        // elkerunk minden itemet a kontenerbol es valogatunk belole 50% szerint
                        foreach (var item in robotInventory.GetItems().Where(i => LootHelper.Roll() && !i.ED.AttributeFlags.NonStackable))
                        {
                            var qtyMod = FastRandom.NextDouble();
                            item.Quantity = (int)(item.Quantity * qtyMod);

                            if (item.Quantity > 0)
                            {
                                lootItems.Add(LootItemBuilder.Create(item.Definition).SetQuantity(item.Quantity).SetRepackaged(item.ED.AttributeFlags.Repackable).Build());
                            }
                            else
                            {
                                robotInventory.RemoveItemOrThrow(item);

                                //toroljuk is le, nem kell ez mar
                                Repository.Delete(item);
                            }
                        }

                        //Check if paint was applied + paint drop chance
                        if (this.ED.Config.Tint != this.Tint && LootHelper.Roll(0.5))
                        {
                            //Paint Query
                            //TODO: performance => cache paints in static collection
                            //TODO: performance => cache if painted, and paint entitydef on undock
                            EntityDefault paint = EntityDefault.Reader.GetAll()
                                                  .Where(i => i.CategoryFlags == CategoryFlags.cf_lottery_items)
                                                  .Where(i => i.Config.Tint == this.Tint)
                                                  .Where(i => i.Name.Contains("paint")).First();
                            if (paint != null)
                            {
                                lootItems.Add(LootItemBuilder.Create(paint.Definition).SetQuantity(1).SetDamaged(false).Build());
                            }
                        }

                        if (lootItems.Count > 0)
                        {
                            var lootContainer = LootContainer.Create().AddLoot(lootItems).BuildAndAddToZone(zone, CurrentPosition);

                            if (lootContainer != null)
                            {
                                var b = TransactionLogEvent.Builder().SetTransactionType(TransactionType.PutLoot).SetCharacter(character).SetContainer(lootContainer.Eid);
                                foreach (var lootItem in lootItems)
                                {
                                    b.SetItem(lootItem.ItemInfo.Definition, lootItem.ItemInfo.Quantity);
                                    Character.LogTransaction(b);
                                }
                            }
                        }

                        var killedByPlayer = (killer != null && killer.IsPlayer());

                        Trashcan.Get().MoveToTrash(this, Session.DisconnectTime, wasInsured, killedByPlayer, Session.InactiveTime);

                        character.NextAvailableRobotRequestTime = DateTime.Now.AddMinutes(killedByPlayer ? ARKHE_REQUEST_TIMER_MINUTES_PVP : ARKHE_REQUEST_TIMER_MINUTES_NPC);

                        Robot activeRobot = null;

                        if (!killedByPlayer)
                        {
                            activeRobot = dockingBase.CreateStarterRobotForCharacter(character);

                            if (activeRobot != null)
                            {
                                Transaction.Current.OnCommited(() =>
                                {
                                    var starterRobotInfo = new Dictionary <string, object>
                                    {
                                        { k.baseEID, Eid },
                                        { k.robotEID, activeRobot.Eid }
                                    };

                                    Message.Builder.SetCommand(Commands.StarterRobotCreated).WithData(starterRobotInfo).ToCharacter(character).Send();
                                });
                            }
                        }

                        character.SetActiveRobot(activeRobot);
                    }
                    else
                    {
                        // mert rendesek vagyunk
                        this.Repair();

                        // csak az adminok miatt kell
                        var container = dockingBase.GetPublicContainer();
                        container.AddItem(this, false);
                    }

                    this.Save();

                    scope.Complete();
                }
                catch (Exception ex)
                {
                    Logger.Exception(ex);
                }
            }
        }
Exemple #47
0
        protected override VideoFrame GetFrame(int n)
        {
            var frame = NewVideoFrame(StaticEnv);

            if (realPlanar)
            {
                OverlayUtils.ResetChroma(frame);
            }
            OverlayUtils.MemSet(frame.GetWritePtr(), byte.MaxValue, frame.GetHeight() * frame.GetPitch());
            var stride    = frame.GetPitch();
            var pixelSize = frame.GetRowSize() / GetVideoInfo().width;
            var random    = new FastRandom(Seed == 0 ? n : Seed);

            unsafe
            {
                void LeftRight(int length, Func <int, int> offset)
                {
                    if (length == 0)
                    {
                        return;
                    }
                    for (var x = 0; x < length; x++)
                    {
                        var data        = (byte *)frame.GetWritePtr() + offset(x) * pixelSize;
                        var gradientVal = GradientVal(x, length);

                        for (var y = 0; y < Height; y++, data += stride)
                        {
                            var val = gradientVal;

                            if (Noise && random.Next(length) > x && random.Next(length) > x)
                            {
                                val = 0;
                            }
                            if (val != byte.MaxValue)
                            {
                                for (var i = 0; i < pixelSize; i++)
                                {
                                    data[i] = val;
                                }
                            }
                        }
                    }
                }

                void TopBottom(int length, Func <int, int> offset)
                {
                    if (length == 0)
                    {
                        return;
                    }
                    for (var y = 0; y < length; y++)
                    {
                        var data        = (byte *)frame.GetWritePtr() + offset(rgb ? (Height - y - 1) : y) * stride;
                        var gradientVal = GradientVal(y, length);

                        for (var x = 0; x < Width; x++, data += pixelSize)
                        {
                            var val = gradientVal;

                            if (Noise && random.Next(length) > y && random.Next(length) > y)
                            {
                                val = 0;
                            }
                            if (val != byte.MaxValue && data[0] > val)
                            {
                                for (var i = 0; i < pixelSize; i++)
                                {
                                    data[i] = val;
                                }
                            }
                        }
                    }
                }

                Parallel.Invoke(() => LeftRight(Left, x => x), () => LeftRight(Right, x => Width - x - 1));
                Parallel.Invoke(() => TopBottom(Top, y => y), () => TopBottom(Bottom, y => Height - y - 1));
            }
            return(frame);
        }
        public override void ProcessPayload(SSPClient client, OperationalSocket _OpSocket)
        {
            RequestHeader reqHeader = Header as RequestHeader;

            if (reqHeader != null)
            {
                Type type = null;
                lock (client.Connection.RegisteredOperationalSockets)
                {
                    client.Connection.RegisteredOperationalSockets.TryGetValue(Identifier, out type);
                }

                if (type != null)
                {
                    bool SendedSuccess = false;
                    try
                    {
                        OperationalSocket OpSocket = (OperationalSocket)Activator.CreateInstance(type, client);

                        OpSocket.isConnected = true;

                        lock (client.Connection.OperationalSockets)
                        {
                            FastRandom rnd = new FastRandom();
                            OpSocket.ConnectionId = (ushort)rnd.Next(1, 65535);
                            while (client.Connection.OperationalSockets.ContainsKey(OpSocket.ConnectionId))
                            {
                                OpSocket.ConnectionId = (ushort)rnd.Next(1, 65535);
                            }

                            client.Connection.OperationalSockets.Add(OpSocket.ConnectionId, OpSocket);
                        }


                        try
                        {
                            OpSocket.onBeforeConnect();
                            client.onOperationalSocket_BeforeConnect(OpSocket);
                        }
                        catch (Exception ex)
                        {
                            SysLogger.Log(ex.Message, SysLogType.Error);
                            OpSocket.onException(ex, ErrorType.UserLand);
                        }

                        client.Connection.SendMessage(new MsgCreateConnectionResponse(OpSocket.ConnectionId, true), new RequestHeader(reqHeader.RequestId, true));
                        SendedSuccess = true;
                        OpSocket.onConnect();
                        client.onOperationalSocket_Connected(OpSocket);
                    }
                    catch (Exception ex)
                    {
                        SysLogger.Log(ex.Message, SysLogType.Error);

                        if (!SendedSuccess)
                        {
                            client.Connection.SendMessage(new MsgCreateConnectionResponse(0, false), new RequestHeader(reqHeader.RequestId, true));
                        }
                    }
                }
                else
                {
                    client.Connection.SendMessage(new MsgCreateConnectionResponse(0, false), new RequestHeader(reqHeader.RequestId, true));
                }
            }
        }
Exemple #49
0
        private void DoSummon(IZone zone)
        {
            Logger.Info("DoSummon starts on zone:" + zone.Id + " " + this);
            if (DeployerPlayer == null)
            {
                Logger.Error("no deployer player " + this);
                return;
            }

            var corporation = DeployerPlayer.Character.GetPrivateCorporation();

            if (corporation == null)
            {
                Logger.Error("no private corporation was found. Deployer character: " + DeployerPlayer.Character);
                DeployerPlayer.Character.SendErrorMessage(new Command("pbsDeployItem"), ErrorCodes.PrivateCorporationAllowedOnly);
                return;
            }

            var            centerTile = CurrentPosition.Center;
            PBSDockingBase dockingBase;

            using (var scope = Db.CreateTransaction())
            {
                try
                {
                    var deployableItem = (Unit)_entityServices.Factory.CreateWithRandomEID(TargetPBSNodeDefault);
                    var zoneStorage    = zone.Configuration.GetStorage();

                    zoneStorage.AddChild(deployableItem);
                    SetStartCore(deployableItem);

                    dockingBase = deployableItem as PBSDockingBase;
                    if (dockingBase != null)
                    {
                        PBSHelper.CreatePBSDockingBase(dockingBase);
                    }

                    deployableItem.Owner           = corporation.Eid;
                    deployableItem.Orientation     = FastRandom.NextInt(0, 3) * 0.25;
                    deployableItem.CurrentPosition = CurrentPosition.Center;

                    if (deployableItem is PBSTurret turret)
                    {
                        // csak a turret kell, gyerekek nem
                        Repository.Insert(turret);
                    }
                    else
                    {
                        // itt mindent insertalunk
                        deployableItem.Save();
                    }

                    Logger.Info("node saved to sql " + deployableItem);

                    Logger.Info("pbs insert start in zoneuser entities: " + deployableItem);
                    zone.UnitService.AddUserUnit(deployableItem, centerTile);

                    Logger.Info("pbs log starting " + deployableItem);
                    PBSHelper.WritePBSLog(PBSLogType.deployed, deployableItem.Eid, deployableItem.Definition, deployableItem.Owner, DeployerPlayer.Character.Id, background: false, zoneId: zone.Id);

                    Transaction.Current.OnCompleted((completed) =>
                    {
                        if (!completed)
                        {
                            Logger.Error("DoSummon rollback " + this);
                            return;
                        }

                        Logger.Info("starting zone enter: " + deployableItem);
                        deployableItem.AddToZone(zone, centerTile);
                        Logger.Info("added to zone " + deployableItem);

                        dockingBase?.OnDockingBaseDeployed();

                        //draw terrain stuff
                        PBSHelper.OnPBSObjectDeployed(zone, deployableItem, true, true, true);
                        Logger.Info("terrain stuff done, sending update. " + deployableItem);

                        //send update
                        ((IPBSObject)deployableItem).SendNodeUpdate();

                        zone.CreateBeam(BeamType.red_20sec,
                                        builder =>
                                        builder.WithPosition(CurrentPosition.Center)
                                        .WithState(BeamState.Hit)
                                        .WithDuration(15000));

                        Logger.Info("pbs node successfully deployed.");
                        _successfulSummon = true;
                    });

                    scope.Complete();
                }
                catch (Exception ex)
                {
                    Logger.Exception(ex);
                }
            }
        }
Exemple #50
0
        public List <BlockWithPosition> Generate(int seed, Vector3I WPos, TreeBluePrint treeType)
        {
            FastRandom rnd = new FastRandom(seed);

            Dictionary <Vector3I, BlockWithPosition> meshDico = new Dictionary <Vector3I, BlockWithPosition>();

            //randomize tree growth level, minimum=2
            int iterations = treeType.Iteration;

            if (treeType.IterationRndLevel > 0)
            {
                iterations -= rnd.Next(treeType.IterationRndLevel);
            }
            if (iterations < 2)
            {
                iterations = 2;                 //Minimum 2, in order to have something correct
            }
            double angleRad       = MathHelper.ToRadians(treeType.Angle);
            double angleOffsetRad = MathHelper.ToRadians(rnd.NextDouble());

            //initialize rotation matrix, position and stacks for branches
            Matrix          rotation         = Matrix.RotationAxis(new Vector3(0, 0, 1), (float)Math.PI / 2.0f);
            Vector3         position         = Vector3.Zero;
            Stack <Matrix>  stackOrientation = new Stack <Matrix>();
            Stack <Vector3> stackPosition    = new Stack <Vector3>();

            //Generate axiom ====================================================================
            string axiom = treeType.Axiom;

            for (int i = 0; i < iterations; i++)
            {
                string temp = "";
                foreach (char axiomChar in axiom)
                {
                    switch (axiomChar)
                    {
                    case 'A':
                        temp += treeType.Rules_a.Rule;
                        break;

                    case 'B':
                        temp += treeType.Rules_b.Rule;
                        break;

                    case 'C':
                        temp += treeType.Rules_c.Rule;
                        break;

                    case 'D':
                        temp += treeType.Rules_d.Rule;
                        break;

                    case 'a':
                        if (treeType.Rules_a.Prob >= rnd.NextDouble())
                        {
                            temp += treeType.Rules_a.Rule;
                        }
                        break;

                    case 'b':
                        if (treeType.Rules_b.Prob >= rnd.NextDouble())
                        {
                            temp += treeType.Rules_b.Rule;
                        }
                        break;

                    case 'c':
                        if (treeType.Rules_c.Prob >= rnd.NextDouble())
                        {
                            temp += treeType.Rules_c.Rule;
                        }
                        break;

                    case 'd':
                        if (treeType.Rules_d.Prob >= rnd.NextDouble())
                        {
                            temp += treeType.Rules_d.Rule;
                        }
                        break;

                    default:
                        temp += axiomChar;
                        break;
                    }
                }
                axiom = temp;
            }

            /* build tree out of generated axiom
             *
             *  Key for Special L-System Symbols used in Axioms
             *
             * M  - move forward one unit with the pen up
             * F  - move forward one unit with the pen down drawing trunks and branches
             * f  - move forward one unit with the pen down drawing leaves
             * A  - replace with rules set A
             * B  - replace with rules set B
             * C  - replace with rules set C
             * D  - replace with rules set D
             * a  - replace with rules set A, taking into account probability set for rule A
             * b  - replace with rules set B, taking into account probability set for rule B
             * c  - replace with rules set C, taking into account probability set for rule C
             * d  - replace with rules set D, taking into account probability set for rule D
             * [  - Push stack states
             * ]  - Pop Stack states
             +  - yaw the turtle right by angle degrees
             + -  - yaw the turtle left by angle degrees
             + &  - pitch the turtle down by angle degrees
             + ^  - pitch the turtle up by angle degrees
             + /  - roll the turtle to the right by angle degrees
             *  - roll the turtle to the left by angle degrees
             */

            int x, y, z;
            BlockWithPosition block;

            foreach (char axiomChar in axiom)
            {
                Matrix  tempRotation = Matrix.Identity;
                Vector3 dir;

                switch (axiomChar)
                {
                case 'M':
                    dir       = new Vector3(1, 0, 0);
                    dir       = Vector3.TransformNormal(dir, rotation);
                    position += dir;
                    break;

                case 'F':

                    //Single Trunk => Always added
                    block = new BlockWithPosition()
                    {
                        isMandatory = true, BlockId = treeType.TrunkBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z)
                    };
                    if (!meshDico.ContainsKey(block.WorldPosition))
                    {
                        meshDico.Add(block.WorldPosition, block);
                    }

                    //Handling other trunk type
                    if (stackOrientation.Count == 0 || (stackOrientation.Count > 0 && treeType.SmallBranches == false))
                    {
                        switch (treeType.TrunkType)
                        {
                        case TrunkType.Double:
                            block = new BlockWithPosition()
                            {
                                isMandatory = true, BlockId = treeType.TrunkBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X + 1, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z)
                            };
                            if (!meshDico.ContainsKey(block.WorldPosition))
                            {
                                meshDico.Add(block.WorldPosition, block);
                            }
                            block = new BlockWithPosition()
                            {
                                isMandatory = true, BlockId = treeType.TrunkBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z + 1)
                            };
                            if (!meshDico.ContainsKey(block.WorldPosition))
                            {
                                meshDico.Add(block.WorldPosition, block);
                            }
                            block = new BlockWithPosition()
                            {
                                isMandatory = true, BlockId = treeType.TrunkBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X + 1, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z + 1)
                            };
                            if (!meshDico.ContainsKey(block.WorldPosition))
                            {
                                meshDico.Add(block.WorldPosition, block);
                            }
                            break;

                        case TrunkType.Crossed:
                            block = new BlockWithPosition()
                            {
                                isMandatory = true, BlockId = treeType.TrunkBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X + 1, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z)
                            };
                            if (!meshDico.ContainsKey(block.WorldPosition))
                            {
                                meshDico.Add(block.WorldPosition, block);
                            }
                            block = new BlockWithPosition()
                            {
                                isMandatory = true, BlockId = treeType.TrunkBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X - 1, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z)
                            };
                            if (!meshDico.ContainsKey(block.WorldPosition))
                            {
                                meshDico.Add(block.WorldPosition, block);
                            }
                            block = new BlockWithPosition()
                            {
                                isMandatory = true, BlockId = treeType.TrunkBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z + 1)
                            };
                            if (!meshDico.ContainsKey(block.WorldPosition))
                            {
                                meshDico.Add(block.WorldPosition, block);
                            }
                            block = new BlockWithPosition()
                            {
                                isMandatory = true, BlockId = treeType.TrunkBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z - 1)
                            };
                            if (!meshDico.ContainsKey(block.WorldPosition))
                            {
                                meshDico.Add(block.WorldPosition, block);
                            }
                            break;

                        default:
                            break;
                        }
                    }

                    //Create foliage "around" trunk, only for "Sub" branch, not the main trunk
                    if (stackOrientation.Count >= treeType.FoliageGenerationStart)
                    {
                        for (x = -treeType.FoliageSize.X; x <= treeType.FoliageSize.X; x++)
                        {
                            for (y = -treeType.FoliageSize.Y; y <= treeType.FoliageSize.Y; y++)
                            {
                                for (z = -treeType.FoliageSize.Z; z <= treeType.FoliageSize.Z; z++)
                                {
                                    //Create only foliage outer form (Not inside)
                                    if (Math.Abs(x) == treeType.FoliageSize.X && Math.Abs(y) == treeType.FoliageSize.Y && Math.Abs(z) == treeType.FoliageSize.Z)
                                    {
                                        continue;
                                    }

                                    block = new BlockWithPosition()
                                    {
                                        BlockId = treeType.FoliageBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X + x, WPos.Y + (int)position.Y + y, WPos.Z + (int)position.Z + z)
                                    };
                                    if (!meshDico.ContainsKey(block.WorldPosition))
                                    {
                                        meshDico.Add(block.WorldPosition, block);
                                    }

                                    //block = new BlockWithPosition() { BlockId = treeType.FoliageBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X + x + 1, WPos.Y + (int)position.Y + y, WPos.Z + (int)position.Z + z) };
                                    //if (!meshDico.ContainsKey(block.WorldPosition)) meshDico.Add(block.WorldPosition, block);
                                    //block = new BlockWithPosition() { BlockId = treeType.FoliageBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X + x - 1, WPos.Y + (int)position.Y + y, WPos.Z + (int)position.Z + z) };
                                    //if (!meshDico.ContainsKey(block.WorldPosition)) meshDico.Add(block.WorldPosition, block);
                                    //block = new BlockWithPosition() { BlockId = treeType.FoliageBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X + x, WPos.Y + (int)position.Y + y, WPos.Z + (int)position.Z + z + 1) };
                                    //if (!meshDico.ContainsKey(block.WorldPosition)) meshDico.Add(block.WorldPosition, block);
                                    //block = new BlockWithPosition() { BlockId = treeType.FoliageBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X + x, WPos.Y + (int)position.Y + y, WPos.Z + (int)position.Z + z - 1) };
                                    //if (!meshDico.ContainsKey(block.WorldPosition)) meshDico.Add(block.WorldPosition, block);
                                }
                            }
                        }
                    }

                    dir = new Vector3(1, 0, 0);
                    Vector3.TransformNormal(ref dir, ref rotation, out dir);
                    position += dir;
                    break;

                case 'f':
                    block = new BlockWithPosition()
                    {
                        BlockId = treeType.FoliageBlock, WorldPosition = new Vector3I(WPos.X + (int)position.X, WPos.Y + (int)position.Y, WPos.Z + (int)position.Z)
                    };
                    if (!meshDico.ContainsKey(block.WorldPosition))
                    {
                        meshDico.Add(block.WorldPosition, block);
                    }
                    dir       = new Vector3(1, 0, 0);
                    dir       = Vector3.TransformNormal(dir, rotation);
                    position += dir;
                    break;

                // Move commands
                case '[':     //Save states
                    stackOrientation.Push(rotation);
                    stackPosition.Push(position);
                    break;

                case ']':     //Load back states
                    rotation = stackOrientation.Pop();
                    position = stackPosition.Pop();
                    break;

                case '+':
                    tempRotation = Matrix.RotationAxis(new Vector3(0, 0, 1), (float)(angleRad + angleOffsetRad));
                    rotation     = tempRotation * rotation;
                    break;

                case '-':
                    tempRotation = Matrix.RotationAxis(new Vector3(0, 0, -1), (float)(angleRad + angleOffsetRad));
                    rotation     = tempRotation * rotation;
                    break;

                case '&':
                    tempRotation = Matrix.RotationAxis(new Vector3(0, 1, 0), (float)(angleRad + angleOffsetRad));
                    rotation     = tempRotation * rotation;
                    break;

                case '^':
                    tempRotation = Matrix.RotationAxis(new Vector3(0, -1, 0), (float)(angleRad + angleOffsetRad));
                    rotation     = tempRotation * rotation;
                    break;

                case '*':
                    tempRotation = Matrix.RotationAxis(new Vector3(1, 0, 0), (float)(angleRad));
                    rotation     = tempRotation * rotation;
                    break;

                case '/':
                    tempRotation = Matrix.RotationAxis(new Vector3(-1, 0, 0), (float)(angleRad));
                    rotation     = tempRotation * rotation;
                    break;

                default:
                    break;
                }
            }

            return(meshDico.Values.ToList());
        }
Exemple #51
0
 public MCMCSampler()
 {
     rnd = new FastRandom();
     TotalSamples = 0L;
 }
        private static void PlaceClustersArea(DesertDescription description, ClusterGroup clusters, Rectangle area, PostPlacementEffect[,] postEffectMap, Point postEffectMapOffset)
        {
            FastRandom fastRandom = new FastRandom(Main.ActiveWorldFileData.Seed).WithModifier(57005uL);
            Vector2    value      = new Vector2(description.Hive.Width, description.Hive.Height);
            Vector2    value2     = new Vector2(clusters.Width, clusters.Height);
            Vector2    value3     = description.BlockScale / 2f;

            for (int i = area.Left; i < area.Right; i++)
            {
                for (int j = area.Top; j < area.Bottom; j++)
                {
                    if (!WorldGen.InWorld(i, j, 1))
                    {
                        continue;
                    }
                    float  num  = 0f;
                    int    num2 = -1;
                    float  num3 = 0f;
                    ushort type = 53;
                    if (fastRandom.Next(3) == 0)
                    {
                        type = 397;
                    }
                    int     num4   = i - description.Hive.X;
                    int     num5   = j - description.Hive.Y;
                    Vector2 value4 = (new Vector2(num4, num5) - value3) / value * value2;
                    for (int k = 0; k < clusters.Count; k++)
                    {
                        Cluster cluster = clusters[k];
                        if (Math.Abs(cluster[0].Position.X - value4.X) > 10f || Math.Abs(cluster[0].Position.Y - value4.Y) > 10f)
                        {
                            continue;
                        }
                        float num6 = 0f;
                        foreach (Block item in cluster)
                        {
                            num6 += 1f / Vector2.DistanceSquared(item.Position, value4);
                        }
                        if (num6 > num)
                        {
                            if (num > num3)
                            {
                                num3 = num;
                            }
                            num  = num6;
                            num2 = k;
                        }
                        else if (num6 > num3)
                        {
                            num3 = num6;
                        }
                    }
                    float num7 = num + num3;
                    Tile  tile = Main.tile[i, j];
                    bool  flag = ((new Vector2(num4, num5) - value3) / value * 2f - Vector2.One).Length() >= 0.8f;
                    PostPlacementEffect postPlacementEffect = PostPlacementEffect.None;
                    if (num7 > 3.5f)
                    {
                        postPlacementEffect = PostPlacementEffect.Smooth;
                        tile.ClearEverything();
                        tile.wall = 187;
                        if (num2 % 15 == 2)
                        {
                            tile.ResetToType(404);
                        }
                    }
                    else if (num7 > 1.8f)
                    {
                        tile.wall = 187;
                        if ((double)j < Main.worldSurface)
                        {
                            tile.liquid = 0;
                        }
                        else
                        {
                            tile.lava(lava: true);
                        }
                        if (!flag || tile.active())
                        {
                            tile.ResetToType(396);
                            postPlacementEffect = PostPlacementEffect.Smooth;
                        }
                    }
                    else if (num7 > 0.7f || !flag)
                    {
                        tile.wall   = 216;
                        tile.liquid = 0;
                        if (!flag || tile.active())
                        {
                            tile.ResetToType(type);
                            postPlacementEffect = PostPlacementEffect.Smooth;
                        }
                    }
                    else if (num7 > 0.25f)
                    {
                        FastRandom fastRandom2 = fastRandom.WithModifier(num4, num5);
                        float      num8        = (num7 - 0.25f) / 0.45f;
                        if (fastRandom2.NextFloat() < num8)
                        {
                            tile.wall = 187;
                            if ((double)j < Main.worldSurface)
                            {
                                tile.liquid = 0;
                            }
                            else
                            {
                                tile.lava(lava: true);
                            }
                            if (tile.active())
                            {
                                tile.ResetToType(type);
                                postPlacementEffect = PostPlacementEffect.Smooth;
                            }
                        }
                    }
                    postEffectMap[i - area.X + postEffectMapOffset.X, j - area.Y + postEffectMapOffset.Y] = postPlacementEffect;
                }
            }
        }
Exemple #53
0
        public static Vector2i[] create(FastRandom rnd)
        {
            HairGender[] array = new HairGender[36]
            {
                HairGender.Unisex,
                HairGender.Male,
                HairGender.Male,
                HairGender.Male,
                HairGender.Male,
                HairGender.Female,
                HairGender.Female,
                HairGender.Male,
                HairGender.Male,
                HairGender.Female,
                HairGender.Unisex,
                HairGender.Female,
                HairGender.Unisex,
                HairGender.Unisex,
                HairGender.Male,
                HairGender.Male,
                HairGender.Unisex,
                HairGender.Male,
                HairGender.Unisex,
                HairGender.Male,
                HairGender.Male,
                HairGender.Female,
                HairGender.Female,
                HairGender.Male,
                HairGender.Male,
                HairGender.Female,
                HairGender.Female,
                HairGender.Unisex,
                HairGender.Male,
                HairGender.Female,
                HairGender.Male,
                HairGender.Male,
                HairGender.Female,
                HairGender.Unisex,
                HairGender.Female,
                HairGender.Male
            };
            Vector2i[] array2 = new Vector2i[6]
            {
                new Vector2i(3, 3),
                new Vector2i(3, 3),
                new Vector2i(3, 5),
                new Vector2i(3, 7),
                new Vector2i(0, 8),
                new Vector2i(3, 0)
            };
            Vector2i[] array3 = new Vector2i[6]
            {
                new Vector2i(9, 4),
                new Vector2i(3, 8),
                new Vector2i(9, 7),
                new Vector2i(3, 8),
                new Vector2i(3, 8),
                new Vector2i(2, 4)
            };
            Vector2i[] array4 = new Vector2i[10];
            int        num    = rnd.Next(36);

            array4[1] = new Vector2i(num % 9, num / 9);
            HairGender hairGender = array[num];
            int        num2       = -1;

            switch (hairGender)
            {
            case HairGender.Male:
                num2 = 0;
                break;

            case HairGender.Female:
                num2 = 1;
                break;

            default:
                num2 = rnd.Next(2);
                break;
            }
            array4[0] = new Vector2i(num2, 0);
            int num3 = rnd.Next(array2.Length);

            array4[4] = array2[num3];
            array4[3] = array3[num3];
            array4[2] = getRandomColor(rnd);
            array4[5] = getRandomColor(rnd);
            array4[6] = getRandomColor(rnd);
            array4[7] = getRandomColor(rnd);
            array4[8] = getRandomColor(rnd);
            return(array4);
        }
 public SpecificBeatmapPatternGenerator(FastRandom random, HitObject hitObject, ManiaBeatmap beatmap, Pattern previousPattern, IBeatmap originalBeatmap)
     : base(random, hitObject, beatmap, previousPattern, originalBeatmap)
 {
 }