Exemple #1
0
        public void Crosbreeding()
        {
            var weights = Config.ParentChances(Population.Count, Population.Select(x => x.Key).ToArray());
            var total   = weights.Sum();


            for (int i = 1; i < weights.Length; i++)
            {
                weights[i] = weights[i] + weights[i - 1];
            }

            while (Population.Count < PopulationCount)
            {
                var indexes = ChooseParents(weights, total);
                NetworkBase <double> female = Population[indexes[0]].Value;
                NetworkBase <double> male   = Population[indexes[1]].Value;

                //Console.WriteLine($"f: {indexes[0]} m:{indexes[1]}");

                NetworkBase <double> child1 = female.Copy();
                NetworkBase <double> child2 = male.Copy();

                RandomNeuronSwap(child1, child2);

                Population.Add(new KeyValuePair <double, NetworkBase <double> >(0, child1));
                if (Population.Count != PopulationCount)
                {
                    Population.Add(new KeyValuePair <double, NetworkBase <double> >(0, child2));
                }
            }
        }
Exemple #2
0
 /// <summary>
 /// Ticks the server, include the network,
 /// and all worlds (and all chunks within those [and all entities within those]).
 /// </summary>
 /// <param name="delta">The time between the last tick and this one</param>
 public static void Tick(double delta)
 {
     Delta           = delta;
     GlobalTickTime += delta;
     try
     {
         NetworkBase.Tick();
     }
     catch (Exception ex)
     {
         SysConsole.Output(OutputType.ERROR, "Error / networktick: " + ex.ToString());
     }
     try
     {
         secondTracker += Delta;
         if (secondTracker >= 1.0)
         {
             secondTracker -= 1.0;
             OncePerSecondTick();
         }
     }
     catch (Exception ex)
     {
         SysConsole.Output(OutputType.ERROR, "Error / oncepersecondtick: " + ex.ToString());
     }
     try
     {
         ServerCommands.Tick();
         ConsoleHandler.CheckInput();
     }
     catch (Exception ex)
     {
         SysConsole.Output(OutputType.ERROR, "Error / command tick: " + ex.ToString());
     }
     try
     {
         for (int i = 0; i < WaitingPlayers.Count; i++)
         {
             if (GlobalTickTime - WaitingPlayers[i].JoinTime > 10)
             {
                 WaitingPlayers.RemoveAt(i);
                 i--;
             }
         }
         for (int i = 0; i < Players.Count; i++)
         {
             // TODO: CVar
             if (GlobalTickTime - Players[i].LastPing > 60 ||
                 GlobalTickTime - Players[i].LastSecondaryPing > 60)
             {
                 DespawnPlayer(Players[i]);
                 i--;
             }
         }
     }
     catch (Exception ex)
     {
         SysConsole.Output(OutputType.ERROR, "Error / general tick: " + ex.ToString());
     }
 }
        /// <summary>
        /// Creates an instance of <seealso cref="AssociationStatisticsRecorder"/>
        /// </summary>
        /// <param name="network"></param>
        public AssociationStatisticsRecorder(NetworkBase network)
        {
            _logInformation = network.LogInformation;

            // hookup network events
            network.AssociationEstablished += OnAssociationEstablished;
            network.MessageReceived        += OnDicomMessageReceived;
            network.MessageSent            += OnDicomMessageSent;
            network.AssociationReleased    += OnAssociationReleased;

            string description;

            if (network is DicomClient)
            {
                description = string.Format("DICOM association from {0} [{1}:{2}] to {3} [{4}:{5}]",
                                            network.AssociationParams.CallingAE,
                                            network.AssociationParams.LocalEndPoint.Address,
                                            network.AssociationParams.LocalEndPoint.Port,
                                            network.AssociationParams.CalledAE,
                                            network.AssociationParams.RemoteEndPoint.Address,
                                            network.AssociationParams.RemoteEndPoint.Port);
            }
            else
            {
                description = string.Format("DICOM association from {0} [{1}:{2}] to {3} [{4}:{5}]",
                                            network.AssociationParams.CallingAE,
                                            network.AssociationParams.RemoteEndPoint.Address,
                                            network.AssociationParams.RemoteEndPoint.Port,
                                            network.AssociationParams.CalledAE,
                                            network.AssociationParams.LocalEndPoint.Address,
                                            network.AssociationParams.LocalEndPoint.Port);
            }

            _assocStats = new TransmissionStatistics(description);
        }
Exemple #4
0
    IEnumerator setupNetworkConnect()
    {
        NetworkBase.Reset();

        yield return(null);

        Debug.Log("开始连接");
        ServiceGate.connect((JsonObject obj) => {
            ServiceGate.queryEntry(((EntryResponse result) => {
                if (result.code == 200)
                {
                    ProgressHUDManager.showHUD("正在连接服务器");
                    int localPort = LocalDataModel.currentLoginPort;
                    LocalDataModel.host = result.host;
                    LocalDataModel.port = (localPort != 0) ? localPort : result.port;

                    ServiceUser.connect((JsonObject connectResult) => {
                        Debug.Log("连接成功");
                        ProgressHUDManager.hideCurrentHUD();

                        SceneManager.LoadScene("Login");
                    });
                }
            }));
        });
    }
        /// <summary>
        /// Инициализировать существующую сеть.
        /// </summary>
        /// <param name="networkId">Идентификатор сети.</param>
        private void InitializeExistingNetwork(int networkId)
        {
            ((Control)tabLearning).Enabled = false;
            tabPanelMain.SelectedIndex = 1;

            // Получить данные сети из базы
            var networkData = _networkService.GetNetworkData(networkId);
            _networkBase = networkData.Network;
            tbNetworkName.Text = _networkBase.Name;

            // Заполнить сеть данными, полученными из БД
            _neuralNetwork.InitializeNetwork(
                networkData.Neurons.Select(e => e.Neuron).ToList(),
                networkData.InputAttributes,
                networkData.Weights);

            // Сформировать пустые кластеры
            _clusters = networkData.Neurons
                .Select(neuron => new NetworkCluster
                {
                    Number = neuron.Neuron.NeuronNumber,
                    NetworkId = neuron.Network?.Network?.NetworkId,
                    Clusters = GetClusters(neuron.Network?.Neurons)
                })
                .ToList();

            _interfaceMediator.DrawClusters(_clusters, tvClusters);
            _interfaceMediator.DrawNetworkWeights(_neuralNetwork, _neuralNetwork.InputAttributes, dgvWeights);
        }
Exemple #6
0
 public void StartServer(int maxConnect = 10)
 {
     network = new NetworkBase();
     network.StartServer(host, port, maxConnect, new StringMessageProtocol());
     InvokeRepeating("UpdateDeoode", 0, DecodeTime);
     InvokeRepeating("CheckHeartbeat", 0, HeartbeatTime);
 }
Exemple #7
0
 public void StartClient()
 {
     network = new NetworkBase();
     network.Connect(host, port, new StringMessageProtocol());
     InvokeRepeating("UpdateDeoode", 0, DecodeTime);
     InvokeRepeating("Heartbeat", 0, HeartbeatTime);
 }
Exemple #8
0
        public void ShouldCrudNeuron()
        {
            IConfigurationRoot configuration = GetConfiguration();

            using (UnitOfWork unitOfWork = new UnitOfWork(configuration))
            {
                NeuronBase  insertedNeuron = null;
                NetworkBase network        = null;
                try
                {
                    network = new NetworkBase()
                    {
                        Name = "Test network"
                    };
                    var networkId = unitOfWork.NetworkRepository.Insert(network);
                    network = unitOfWork.NetworkRepository.GetByID(networkId);

                    // Create
                    var neuron = new NeuronBase()
                    {
                        NetworkId    = network.NetworkId,
                        NeuronNumber = 2
                    };
                    var id = unitOfWork.NeuronRepository.Insert(neuron);
                    Assert.IsTrue(id > 0);

                    // Read
                    insertedNeuron = unitOfWork.NeuronRepository.GetByID(id);
                    Assert.IsNotNull(insertedNeuron);
                    Assert.AreEqual(id, insertedNeuron.NeuronId);

                    // Update
                    insertedNeuron.NeuronNumber = 3;
                    unitOfWork.NeuronRepository.Update(insertedNeuron);

                    insertedNeuron = unitOfWork.NeuronRepository.GetByID(id);
                    Assert.IsNotNull(insertedNeuron);
                    Assert.AreEqual(id, insertedNeuron.NeuronId);
                    Assert.AreEqual(3, insertedNeuron.NeuronNumber);

                    // Delete
                    unitOfWork.NeuronRepository.Delete(insertedNeuron);
                    insertedNeuron = unitOfWork.NeuronRepository.GetByID(id);
                    Assert.IsNull(insertedNeuron);
                }
                finally
                {
                    if (insertedNeuron != null)
                    {
                        unitOfWork.NeuronRepository.Delete(insertedNeuron);
                    }
                    if (network != null)
                    {
                        unitOfWork.NetworkRepository.Delete(network);
                    }
                }
            }
        }
Exemple #9
0
    void StartClient()
    {
        hasStarted = true;
        Debug.Log("Started client");
        networkBase = new GameClient(client);
        GameClient gclient = networkBase as GameClient;

        gclient.StartClient();
    }
Exemple #10
0
        public void ShouldCrudInputAttribute()
        {
            IConfigurationRoot configuration = GetConfiguration();

            using (UnitOfWork unitOfWork = new UnitOfWork(configuration))
            {
                InputAttributeBase insertedInputAttribute = null;
                NetworkBase        network = null;
                try
                {
                    // Create
                    network = new NetworkBase()
                    {
                        Name = "New test network"
                    };
                    var networkId = unitOfWork.NetworkRepository.Insert(network);
                    network = unitOfWork.NetworkRepository.GetByID(networkId);

                    var inputAttribute = new InputAttributeBase()
                    {
                        Name      = "Test Attribute",
                        NetworkId = networkId
                    };
                    var attributeId = unitOfWork.InputAttributeRepository.Insert(inputAttribute);

                    // Read
                    insertedInputAttribute = unitOfWork.InputAttributeRepository.GetByID(attributeId);
                    Assert.IsNotNull(insertedInputAttribute);
                    Assert.AreEqual(attributeId, insertedInputAttribute.InputAttributeId);

                    // Update
                    insertedInputAttribute.Name = "Updated Test Attribute";
                    unitOfWork.InputAttributeRepository.Update(insertedInputAttribute);

                    insertedInputAttribute = unitOfWork.InputAttributeRepository.GetByID(attributeId);
                    Assert.IsNotNull(insertedInputAttribute);
                    Assert.AreEqual(attributeId, insertedInputAttribute.InputAttributeId);
                    Assert.AreEqual("Updated Test Attribute", insertedInputAttribute.Name);

                    // Delete
                    unitOfWork.InputAttributeRepository.Delete(insertedInputAttribute);
                    insertedInputAttribute = unitOfWork.InputAttributeRepository.GetByID(attributeId);
                    Assert.IsNull(insertedInputAttribute);
                }
                finally
                {
                    if (insertedInputAttribute != null)
                    {
                        unitOfWork.InputAttributeRepository.Delete(insertedInputAttribute);
                    }
                    if (network != null)
                    {
                        unitOfWork.NetworkRepository.Delete(network);
                    }
                }
            }
        }
 public PDataTFStream(NetworkBase networkBase, byte pcid, uint max, uint total, bool combineCommandData)
 {
     _command            = true;
     _pcid               = pcid;
     _max                = max;
     _pdu                = new PDataTF();
     _buffer             = new MemoryStream((int)total + 1024);
     _networkBase        = networkBase;
     _combineCommandData = combineCommandData;
 }
Exemple #12
0
    void StartServer()
    {
        hasStarted = true;
        isServer   = true;
        Debug.Log("Started server");
        networkBase = new GameServer(client);
        GameServer server = networkBase as GameServer;

        server.StartGame(new NetworkBase.UDPClient[] { Connectedclient });
    }
Exemple #13
0
        public PDataTFStream(NetworkBase networkBase, byte pcid, uint max, bool combineCommandData)
        {
            _command = true;
            _pcid    = pcid;
            _max     = max;
            _pdu     = new PDataTFWrite(max);
            _pdu.CreatePDV(pcid);

            _networkBase        = networkBase;
            _combineCommandData = combineCommandData;
            BytesWritten        = 0;
        }
Exemple #14
0
 public void RandomNeuronSwap(NetworkBase <double> child1, NetworkBase <double> child2)
 {
     for (int i = 0; i < child1.LayerCount; i++)
     {
         for (int k = 0; k < child1.Layers[i].NeuronCount; k++)
         {
             if (Random.NextBoolean())
             {
                 var tmp = child1.Layers[i].Neurons[k];
                 child1.Layers[i].Neurons[k] = child2.Layers[i].Neurons[k];
                 child2.Layers[i].Neurons[k] = tmp;
             }
         }
     }
 }
        public void NewRandomPopulation(int populationCount, List <int> layerCount, List <Type> neuronTypes)
        {
            Generation        = 0;
            PopulationCount   = populationCount;
            Population        = new NetworkBase <double> [PopulationCount];
            LearningAlgorithm = new GeneticAlgorithm();


            var builder = Builder.GetBuilder(layerCount, neuronTypes);

            for (int i = 0; i < PopulationCount; i++)
            {
                Population[i] = builder.GetEmpty().Randomize();
            }
        }
Exemple #16
0
        private static void SetupConnection()
        {
            if (NetworkBase.ClientNetwork == null || !NetworkBase.ClientNetwork.Connected)
            {
                string[] ServerInfo = ServerData.Read();

                if (NetworkBase.Setup(ServerInfo[0], Convert.ToInt32(ServerInfo[1])))
                {
                    Debug.Log("Попытка соединиться с сервером", ConsoleColor.Cyan);
                    ConnectToServer();
                }
                else
                {
                    Debug.LogError("Не удаётся установить соединение с сервером!");
                }
            }
        }
        public static double Identify(this NetworkBase <double> network)
        {
            double sum = 0;

            foreach (var layer in network.Layers)
            {
                foreach (var neuron in layer.Neurons)
                {
                    var weights = neuron.GetWeights();
                    for (var i = 0; i < weights.Length; i++)
                    {
                        sum += weights[i];
                    }
                }
            }
            return(sum);
        }
Exemple #18
0
        public void ShouldCrudNetwork()
        {
            IConfigurationRoot configuration = GetConfiguration();

            using (UnitOfWork unitOfWork = new UnitOfWork(configuration))
            {
                NetworkBase insertedNetwork = null;
                try
                {
                    // Create
                    var network = new NetworkBase()
                    {
                        Name = "New test network"
                    };
                    var id = unitOfWork.NetworkRepository.Insert(network);
                    Assert.IsTrue(id > 0);

                    // Read
                    insertedNetwork = unitOfWork.NetworkRepository.GetByID(id);
                    Assert.IsNotNull(insertedNetwork);
                    Assert.AreEqual(id, insertedNetwork.NetworkId);

                    // Update
                    insertedNetwork.Name = "Updated test network";
                    unitOfWork.NetworkRepository.Update(insertedNetwork);

                    insertedNetwork = unitOfWork.NetworkRepository.GetByID(id);
                    Assert.IsNotNull(insertedNetwork);
                    Assert.AreEqual(id, insertedNetwork.NetworkId);
                    Assert.AreEqual("Updated test network", insertedNetwork.Name);

                    // Delete
                    unitOfWork.NetworkRepository.Delete(insertedNetwork);
                    insertedNetwork = unitOfWork.NetworkRepository.GetByID(id);
                    Assert.IsNull(insertedNetwork);
                }
                finally
                {
                    if (insertedNetwork != null)
                    {
                        unitOfWork.NetworkRepository.Delete(insertedNetwork);
                    }
                }
            }
        }
Exemple #19
0
    // Use this for initialization
    void Awake()
    {
        GameObject splatTest = new GameObject("splatTest");
        Splat      splt      = splatTest.AddComponent <Splat>();



        instance = this;
        GameObject[] tempBlocks = GameObject.FindGameObjectsWithTag("Walkable");
        GameObject[] tempPass   = GameObject.FindGameObjectsWithTag("PassThrough");
        blocks = new GameObject[tempBlocks.Length + tempPass.Length];
        List <GameObject> listTempBlocks = new List <GameObject>();
        List <GameObject> toBeRemoved    = new List <GameObject>();

        for (int i = 0; i < tempBlocks.Length; i++)
        {
            listTempBlocks.Add(tempBlocks[i]);
            if (tempBlocks[i].name.Contains("ItemBlock") || tempBlocks[i].transform.position.y > 2.0f)
            {
                toBeRemoved.Add(tempBlocks[i]);
            }
        }

        for (int i = 0; i < tempPass.Length; i++)
        {
            listTempBlocks.Add(tempPass[i]);
        }
        for (int i = listTempBlocks.Count - 1; i >= 0; i--)
        {
            if (listTempBlocks.Find(x => Mathf.Abs(x.transform.position.x - listTempBlocks[i].transform.position.x) < 0.1f && x.transform.position.y > listTempBlocks[i].transform.position.y && x.transform.position.y - listTempBlocks[i].transform.position.y < 0.5f) != null)
            {
                toBeRemoved.Add(listTempBlocks[i]);
            }
        }
        for (int i = toBeRemoved.Count - 1; i >= 0; i--)
        {
            //if(toBeRemoved[i] != null)
            //    toBeRemoved[i].transform.position = new Vector2(999, 999);    //to visually show which blocks cannot be spawned on
            listTempBlocks.Remove(toBeRemoved[i]);
        }
        blocks = listTempBlocks.ToArray();
        NetworkBase b = new NetworkBase(new System.Net.Sockets.UdpClient());
    }
Exemple #20
0
        private static NetworkBase <double> Rand(NetworkBase <double> network, RandomizerOptions options = null)
        {
            if (options == null)
            {
                options = new RandomizerOptions(-1, 1);
            }

            foreach (var layer in network.Layers)
            {
                foreach (var neuron in layer.Neurons)
                {
                    var count   = neuron.GetCount();
                    var weights = new double[count];
                    for (int i = 0; i < count; i++)
                    {
                        weights[i] = options.Uniform.NextDouble();
                    }
                    neuron.SetWeights(weights);
                }
            }

            return(network);
        }
Exemple #21
0
        public static NetworkBase <double> Copy(this NetworkBase <double> network)
        {
            var builder = new Builder().SetInput(network.InputCount);

            foreach (var layer in network.Layers)
            {
                builder.AddLayer(layer.NeuronCount, layer.Neurons[0].GetType());
            }
            var result = builder.GetEmpty();

            for (int i = 0; i < network.LayerCount; i++)
            {
                int count = network.Layers[i].InputCount;
                for (int k = 0; k < network.Layers[i].NeuronCount; k++)
                {
                    var w       = network.Layers[i].Neurons[k].GetWeights();
                    var weights = new double[w.Length];
                    w.CopyTo(weights, 0);
                    result.Layers[i].Neurons[k].SetWeights(weights);
                }
            }
            return(result);
        }
Exemple #22
0
        private void TestBtn_Copy_Click(object sender, RoutedEventArgs e)
        {
            if (this.network == null)
            {
                return;
            }
            var classesCount    = 0;
            var attributesCount = 0;
            var csvData         = this.GetSetFromFile(ref classesCount, ref attributesCount, true);

            if (csvData == null)
            {
                return;
            }
            var dataSet = csvData.NormalizedData;

            var resX = new List <double>(dataSet.Count);
            var resY = new List <double>(dataSet.Count);

            var lowX  = dataSet.Min(x => x.Item1[0]);
            var highX = dataSet.Max(x => x.Item1[0]);
            var lowY  = dataSet.Min(x => x.Item1[1]);
            var highY = dataSet.Max(x => x.Item1[1]);

            var data = dataSet.Select(x => new { x = x.Item1[0], y = x.Item1[1], resCls = NetworkBase.GetClass(this.network.Predict(x.Item1)) });

            this.DrawChart(
                "Trained results",
                data.GroupBy(x => x.resCls)
                .Select(x => x.Select(y => new Tuple <double, double>(y.x, y.y))),
                lowX,
                highX,
                lowY,
                highY
                );

            SaveFileDialog saveFileDlg = new SaveFileDialog();

            saveFileDlg.Filter = "csv files (*.csv)|*.txt|All files (*.*)|*.*";
            var c = new CultureInfo("en-US");

            if (saveFileDlg.ShowDialog() == true)
            {
                File.WriteAllLines
                (
                    saveFileDlg.FileName,
                    data.Zip(csvData.RawData, (f, s) => $"{s.Item1[0].ToString(c)},{s.Item1[1].ToString(c)},{f.resCls + 1}")
                );
            }
        }
Exemple #23
0
        private void TestBtnClick(object sender, RoutedEventArgs e)
        {
            if (this.network == null)
            {
                return;
            }
            int classesCount = 0, attributesCount = 0;
            var testSet = this.GetSetFromFile(ref classesCount, ref attributesCount)?.NormalizedData;

            if (testSet is null)
            {
                return;
            }
            var resX = new List <double>(testSet.Count);
            var resY = new List <double>(testSet.Count);

            var lowX  = testSet.Min(x => x.Item1[0]);
            var highX = testSet.Max(x => x.Item1[0]);
            var lowY  = 0.0;
            var highY = 0.0;

            if (networkType is ClassificationNetwork)
            {
                lowY  = testSet.Min(x => x.Item1[1]);
                highY = testSet.Max(x => x.Item1[1]);
            }
            else if (networkType is RegressionNetwork)
            {
                lowY  = testSet.Min(x => x.Item2[0]);
                highY = testSet.Max(x => x.Item2[0]);
            }
            if (networkType is ClassificationNetwork)
            {
                this.DrawChart
                (
                    "Correct results",
                    testSet.GroupBy(x => x.Item2.IndexOf(1.0)).Select(g => g.Select(x => new Tuple <double, double>(x.Item1[0], x.Item1[1]))),
                    lowX,
                    highX,
                    lowY,
                    highY
                );
            }
            else
            {
                this.DrawChart
                (
                    "Correct results",
                    testSet.GroupBy(x => x.Item2.IndexOf(1.0)).Select(g => g.Select(x => new Tuple <double, double>(x.Item1[0], x.Item2[0]))),
                    lowX,
                    highX,
                    lowY,
                    highY
                );
            }

            var data = testSet.Select(x => new { x = x.Item1[0], y = x.Item1[1], cls = NetworkBase.GetClass(x.Item2), resCls = NetworkBase.GetClass(this.network.Predict(x.Item1)) });

            if (networkType is RegressionNetwork)
            {
                data = testSet.Select(x => new { x = x.Item1[0], y = this.network.Predict(x.Item1).First(), cls = NetworkBase.GetClass(x.Item2), resCls = NetworkBase.GetClass(this.network.Predict(x.Item2)) });
            }
            var acc = data.Count(x => x.cls == x.resCls) / (double)data.Count() * 100;

            this.DrawChart(
                "Trained results",
                data.GroupBy(x => x.resCls)
                .Select(x => x.Select(y => new Tuple <double, double>(y.x, y.y))),
                lowX,
                highX,
                lowY,
                highY
                );
            this.AccLbl.Content = acc.ToString();
        }
Exemple #24
0
 internal static void SetNetwork(NetworkBase network)
 {
     instance = new NetCommander(network);
 }
Exemple #25
0
 private NetCommander(NetworkBase network)
 {
     NetReference = network;
 }
 public void SetNeuralNetwork(NetworkBase <double> network)
 {
     NeuralNetwork     = network;
     LastSensorReading = null;
 }
Exemple #27
0
        /// <summary>
        /// Starts up the server.
        /// </summary>
        public static void Init()
        {
            SysConsole.Output(OutputType.INIT, "Loading server...");
            SysConsole.Output(OutputType.INIT, "Loading command engine (Frenetic)...");
            Outputter op = new ServerOutputter();

            ServerCommands.Init(op);
            ServerCVar.Init(op);
            SysConsole.Output(OutputType.INIT, "Loading console reader...");
            ConsoleHandler.Init();
            SysConsole.Output(OutputType.INIT, "Preparing world system...");
            Worlds = new List <World>();
            SysConsole.Output(OutputType.INIT, "Loading networking engine...");
            NetworkBase.Init(true);
            SysConsole.Output(OutputType.INIT, "Loading player command engine...");
            PlayerCommandEngine.Init();
            SysConsole.Output(OutputType.INIT, "Preparing default worlds...");
            // TEMPORARY; TODO: Read settings / command line / anything
            CreateWorld("world");
            SysConsole.Output(OutputType.INIT, "Preparing to tick...");
            // Tick
            double    TARGETFPS    = 40d;
            Stopwatch Counter      = new Stopwatch();
            Stopwatch DeltaCounter = new Stopwatch();

            DeltaCounter.Start();
            double TotalDelta   = 0;
            double CurrentDelta = 0d;
            double TargetDelta  = 0d;
            int    targettime   = 0;

            while (true)
            {
                // Update the tick time usage counter
                Counter.Reset();
                Counter.Start();
                // Update the tick delta counter
                DeltaCounter.Stop();
                // Delta time = Elapsed ticks * (ticks/second)
                CurrentDelta = ((double)DeltaCounter.ElapsedTicks) / ((double)Stopwatch.Frequency);
                // How much time should pass between each tick ideally
                TARGETFPS = ServerCVar.g_fps.ValueD;
                if (TARGETFPS < 1 || TARGETFPS > 100)
                {
                    ServerCVar.g_fps.Set("40");
                    TARGETFPS = 40;
                }
                TargetDelta = (1d / TARGETFPS);
                // How much delta has been built up
                TotalDelta += CurrentDelta;
                if (TotalDelta > TargetDelta * 10)
                {
                    // Lagging - cheat to catch up!
                    TargetDelta *= 3;
                }
                if (TotalDelta > TargetDelta * 10)
                {
                    // Lagging a /lot/ - cheat /extra/ to catch up!
                    TargetDelta *= 3;
                }
                if (TotalDelta > TargetDelta * 10)
                {
                    // At this point, the server's practically dead.
                    TargetDelta *= 3;
                }
                // Give up on acceleration at this point. 50 * 27 = 1.35 seconds / tick under a default tickrate.
                // As long as there's more delta built up than delta wanted, tick
                while (TotalDelta > TargetDelta)
                {
                    Tick(TargetDelta);
                    TotalDelta -= TargetDelta;
                }
                // Begin the delta counter to find out how much time is /really/ slept for
                DeltaCounter.Reset();
                DeltaCounter.Start();
                // The tick is done, stop measuring it
                Counter.Stop();
                // Only sleep for target milliseconds/tick minus how long the tick took... this is imprecise but that's okay
                targettime = (int)((1000d / TARGETFPS) - Counter.ElapsedMilliseconds);
                // Only sleep at all if we're not lagging
                if (targettime > 0)
                {
                    // Try to sleep for the target time - very imprecise, thus we deal with precision inside the tick code
                    Thread.Sleep(targettime);
                }
            }
        }
Exemple #28
0
    // Update is called once per frame
    void Update()
    {
        if (networkBase == null)
        {
            int ownPlayers = 1;
            //if (Input.GetKeyDown(KeyCode.N))RequestMatch();
            if (Input.GetKeyDown(KeyCode.V))
            {
                byte[] data = new byte[1];
                SendToClient(new NetworkBase.UDPClient("0.0.0.9", 999), data);
                networkBase = new GameServer(client, 2);
                isServer    = true;
                //client.BeginReceive(new AsyncCallback(networkBase.receiveCallback), client);
                //client.BeginReceive(new AsyncCallback(receive), null);
                GameServer server = networkBase as GameServer;
                server.MakeLobby("lobby123", ownPlayers);
                client.BeginReceive(new AsyncCallback(networkBase.receiveCallback), client);
            }

            if (Input.GetKeyDown(KeyCode.N))
            {
                byte[] data = new byte[1];
                SendToClient(new NetworkBase.UDPClient("0.0.0.9", 999), data);
                networkBase = new GameClient(client);

                //client.BeginReceive(new AsyncCallback(networkBase.receiveCallback), client);
                //client.BeginReceive(new AsyncCallback(receive), null);
                GameClient server = networkBase as GameClient;
                server.controllingPlayers = ownPlayers;
                server.JoinLobby("lobby123", ownPlayers);
                client.BeginReceive(new AsyncCallback(networkBase.receiveCallback), client);
            }

            //testing
            //if (Input.GetKeyDown(KeyCode.N)) StartServer();
            //if (Input.GetKeyDown(KeyCode.N)) StartClient();
        }
        else
        {
            if (networkBase.isReady)
            {
                networkBase.Update();
            }
            else
            {
                if (Input.GetKeyDown(KeyCode.B) && isServer)
                {
                    GameServer s = networkBase as GameServer;
                    s.StartLobby();
                }
            }
            if (!startedServer && isServer && networkBase.isReady)
            {
                startedServer = true;
                GameServer server = networkBase as GameServer;
                StartCoroutine(server.UpdateServer());
            }
            if (!startedServer && !isServer && networkBase.isReady)
            {
                startedServer = true;
                GameClient gameclient = networkBase as GameClient;
                StartCoroutine(gameclient.UpdateClient());
            }
        }
    }
Exemple #29
0
 public void Reset()
 {
     networkBase = null;
 }
Exemple #30
0
 public static NetworkBase <double> Randomize(this NetworkBase <double> network, RandomizerOptions options = null)
 {
     return(Rand(network, options));
 }
Exemple #31
0
        private void TrainBtnClick(object sender, RoutedEventArgs e)
        {
            double learningRate;
            double momentum;
            int    iterations;

            if (TypeComboBox.SelectedItem is null)
            {
                return;
            }
            if (TypeComboBox.SelectedValue.ToString() == "Classification")
            {
                networkType = new ClassificationNetwork();
            }
            else
            {
                networkType = new RegressionNetwork();
            }
            int classesCount    = 0;
            int attributesCount = 0;

            if (!Double.TryParse(this.EtaTb.Text, out learningRate))
            {
                return;
            }
            if (!Double.TryParse(this.AlphaTb.Text, out momentum))
            {
                return;
            }


            // parse neuron counts separated by commas
            var neurons = this.HiddenNeuronsTb.Text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x =>
            {
                var res = 0;
                if (!Int32.TryParse(x, out res))
                {
                    return(0);
                }
                return(res);
            }).ToList();

            if (neurons.Any(x => x <= 0))
            {
                return;
            }

            if (!Int32.TryParse(this.IterationsTb.Text, out iterations))
            {
                return;
            }
            var trainSet = this.GetSetFromFile(ref classesCount, ref attributesCount)?.NormalizedData;

            if (trainSet == null)
            {
                return;
            }
            // TODO: permit user to model network and edit parameters
            int         outputNeurons      = classesCount;
            IActivation activationFunction = new SigmoidFunction();

            if (networkType is RegressionNetwork)
            {
                outputNeurons      = 1;
                activationFunction = new IdentityFunction();
            }
            this.network = new Network().BuildNetwork(attributesCount, neurons, outputNeurons, learningRate, momentum, activationFunction, networkType);

            var tb = ShowWaitingDialog();

            Task.Run(() =>
            {
                var errors = this.network.Train(trainSet, iterations);

                tb.Dispatcher.Invoke(() =>
                {
                    this.DrawChart
                    (
                        "Error function",
                        new List <IEnumerable <Tuple <double, double> > >()
                    {
                        Enumerable.Range(1, iterations).Zip(errors, (it, val) => new Tuple <double, double>((double)it, val))
                    },
                        1,
                        iterations,
                        errors.Min(),
                        errors.Max()
                    );
                    DialogHost.CloseDialogCommand.Execute(null, tb);
                });
            });

            // TODO: update GUI
        }
Exemple #32
0
        /// <summary>
        /// Called when the window is loading, only to be used by the startup process.
        /// </summary>
        void Window_Load(object sender, EventArgs e)
        {
            SysConsole.Output(OutputType.CLIENTINIT, "Window generated!");
            DPIScale = Window.Width / CVars.r_width.ValueF;
            SysConsole.Output(OutputType.CLIENTINIT, "DPIScale is " + DPIScale + "!");
            SysConsole.Output(OutputType.CLIENTINIT, "Setting up a game engine backend placeholder...");
            FakeEngine();
            SysConsole.Output(OutputType.CLIENTINIT, "Loading base textures...");
            PreInitRendering();
            Textures = new TextureEngine();
            Textures.InitTextureSystem(Files);
            ItemFrame        = Textures.GetTexture("ui/hud/item_frame");
            CWindow.Textures = Textures;
            SysConsole.Output(OutputType.CLIENTINIT, "Loading shaders...");
            Shaders    = new ShaderEngine();
            GLVendor   = GL.GetString(StringName.Vendor);
            GLVersion  = GL.GetString(StringName.Version);
            GLRenderer = GL.GetString(StringName.Renderer);
            SysConsole.Output(OutputType.CLIENTINIT, "Vendor: " + GLVendor + ", GLVersion: " + GLVersion + ", Renderer: " + GLRenderer);
            if (GLVendor.ToLowerFast().Contains("intel"))
            {
                SysConsole.Output(OutputType.CLIENTINIT, "Disabling good graphics (Appears to be Intel: '" + GLVendor + "')");
                Shaders.MCM_GOOD_GRAPHICS = false;
            }
            Shaders.InitShaderSystem();
            CWindow.Shaders = Shaders;
            Engine.GetShaders();
            GraphicsUtil.CheckError("Load - Shaders");
            SysConsole.Output(OutputType.CLIENTINIT, "Loading animation engine...");
            Animations         = new AnimationEngine();
            CWindow.Animations = Animations;
            SysConsole.Output(OutputType.CLIENTINIT, "Loading model engine...");
            Models = new ModelEngine();
            Models.Init(Animations, CWindow);
            LODHelp        = new ModelLODHelper(this);
            CWindow.Models = Models;
            SysConsole.Output(OutputType.CLIENTINIT, "Loading rendering helper...");
            Rendering = new Renderer(Textures, Shaders, Models);
            Rendering.Init();
            CWindow.Rendering3D = Rendering;
            CWindow.Rendering2D = new Renderer2D(Textures, Shaders);
            CWindow.Rendering2D.Init();
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing load screen...");
            load_screen = Textures.GetTexture("ui/menus/loadscreen");
            Establish2D();
            SWLoading.Start();
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Loading block textures...");
            TBlock = new TextureBlock();
            TBlock.Generate(this, CVars, Textures, false);
            GraphicsUtil.CheckError("Load - Textures");
            SysConsole.Output(OutputType.CLIENTINIT, "Loading fonts...");
            Fonts = new GLFontEngine(Textures, Shaders);
            Fonts.Init(Files);
            FontSets = new FontSetEngine(Fonts);
            FontSets.Init((subdat) => Languages.GetText(Files, subdat), () => Ortho, () => GlobalTickTimeLocal);
            GraphicsUtil.CheckError("Load - Fonts");
            PassLoadScreen();
            CWindow.FontSets = FontSets;
            CWindow.GLFonts  = Fonts;
            SysConsole.Output(OutputType.CLIENTINIT, "Loading general graphics settings...");
            CVars.r_vsync.OnChanged += OnVsyncChanged;
            OnVsyncChanged(CVars.r_vsync, EventArgs.Empty);
            CVars.r_cloudshadows.OnChanged += OnCloudShadowChanged;
            CVars.r_transpll.OnChanged     += OnLLChanged;
            OnLLChanged(CVars.r_transpll, EventArgs.Empty);
            GraphicsUtil.CheckError("Load - General Graphics");
            SysConsole.Output(OutputType.CLIENTINIT, "Loading UI engine...");
            UIConsole.InitConsole(); // TODO: make this non-static
            InitChatSystem();
            PassLoadScreen();
            GraphicsUtil.CheckError("Load - UI");
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing rendering engine...");
            InitRendering();
            GraphicsUtil.CheckError("Load - Rendering");
            SysConsole.Output(OutputType.CLIENTINIT, "Loading particle effect engine...");
            Particles = new ParticleHelper(this)
            {
                Engine = new ParticleEngine(this)
            };
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing mouse and keyboard handlers...");
            KeyHandler.Init();
            Gamepad = new GamePadHandler();
            Gamepad.Init(this);
            PassLoadScreen();
            GraphicsUtil.CheckError("Load - Keyboard/mouse");
            SysConsole.Output(OutputType.CLIENTINIT, "Building the sound system...");
            Sounds.Init(Engine);
            GraphicsUtil.CheckError("Load - Sound");
            SysConsole.Output(OutputType.CLIENTINIT, "Building game world...");
            BuildWorld();
            PassLoadScreen();
            GraphicsUtil.CheckError("Load - World");
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing networking...");
            Network = new NetworkBase(this);
            RegisterDefaultEntityTypes();
            GraphicsUtil.CheckError("Load - Net");
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Loading Voxel computer...");
            try
            {
                VoxelComputer = new VoxelComputeEngine();
                VoxelComputer.Init(this);
            }
            catch (Exception ex)
            {
                SysConsole.Output(ex);
            }
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Playing background music...");
            BackgroundMusic();
            CVars.a_musicvolume.OnChanged += OnMusicVolumeChanged;
            CVars.a_musicpitch.OnChanged  += OnMusicPitchChanged;
            CVars.a_music.OnChanged       += OnMusicChanged;
            CVars.a_echovolume.OnChanged  += OnEchoVolumeChanged;
            OnEchoVolumeChanged(null, null);
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Setting up screens...");
            TheMainMenuScreen         = new MainMenuScreen(this);
            TheGameScreen             = new GameScreen(this);
            TheSingleplayerMenuScreen = new SingleplayerMenuScreen(this);
            TheLoadScreen             = new LoadScreen(this);
            CScreen = TheMainMenuScreen;
            SysConsole.Output(OutputType.CLIENTINIT, "Trying to grab RawGamePad...");
            try
            {
                RawGamePad = new XInput();
            }
            catch (Exception ex)
            {
                SysConsole.Output(OutputType.CLIENTINIT, "Failed to grab RawGamePad: " + ex.Message);
            }
            SysConsole.Output(OutputType.CLIENTINIT, "Preparing inventory...");
            InitInventory();
            PassLoadScreen();
            SysConsole.Output(OutputType.CLIENTINIT, "Creating sky...");
            CreateSkyBox();
            SysConsole.Output(OutputType.CLIENTINIT, "Requesting a menu server...");
            LocalServer?.ShutDown();
            LocalServer = new Server(28009)
            {
                IsMenu = true
            };                                                 // TODO: Grab first free port?
            Object locky = new Object();
            bool   ready = false;

            Schedule.StartAsyncTask(() =>
            {
                LocalServer.StartUp("menu", () =>
                {
                    lock (locky)
                    {
                        ready = true;
                    }
                });
            });
            while (true)
            {
                lock (locky)
                {
                    if (ready)
                    {
                        break;
                    }
                }
                PassLoadScreen();
                Thread.Sleep(50);
            }
            SysConsole.Output(OutputType.CLIENTINIT, "Connecting to a menu server...");
            Network.LastConnectionFailed = false;
            Network.Connect("localhost", "28009", true, null); // TODO: Grab accurate local IP?
            Stopwatch sw = new Stopwatch();

            sw.Start();
            bool annc = false;

            while (true)
            {
                if (Network.LastConnectionFailed)
                {
                    SysConsole.Output(OutputType.CLIENTINIT, "Failed to connect to menu server! Failing!");
                    Window.Close();
                    return;
                }
                if (Network.IsAlive)
                {
                    break;
                }
                sw.Stop();
                long ms = sw.ElapsedMilliseconds;
                sw.Start();
                if (ms > 10000 && !annc)
                {
                    annc = true;
                    SysConsole.Output(OutputType.WARNING, "Taking weirdly long, did something fail?!");
                }
                if (ms > 20000)
                {
                    SysConsole.Output(OutputType.CLIENTINIT, "Timed out while trying to connect to menu server! Failing!");
                    Window.Close();
                    return;
                }
                PassLoadScreen();
                Thread.Sleep(50);
            }
            SysConsole.Output(OutputType.CLIENTINIT, "Showing main menu...");
            ShowMainMenu();
            GraphicsUtil.CheckError("Load - Final");
            SysConsole.Output(OutputType.CLIENTINIT, "Ready and looping!");
        }
Exemple #33
0
 internal static HandleRef getCPtr(NetworkBase obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }