static void NatUtility_OpenPort(NatDeviceState device, int port)
        {
            lock (syncLock) {
                Mapping mapping = new Mapping(Protocol.Udp, port, port);
                device.Nat.BeginCreatePortMap(mapping, ar => {
                    lock (syncLock) {
                        try {
                            device.Nat.EndCreatePortMap(ar);

                            // finish this
                            NatUtility_OpenPort_Finish(device, port);
                        }
                        catch (MappingException exn) {
                            if (exn.ErrorCode == 718)
                            {
                                NatUtility_OpenPort_Finish(device, port);
                            }
                            else
                            {
                                BoltLog.Exception(exn);
                            }
                        }
                        catch (Exception exn) {
                            BoltLog.Exception(exn);
                        }
                    }
                }, null);
            }
        }
示例#2
0
        public void SendData()
        {
            var now = Time.timeSinceLevelLoad;

            if (BoltNetwork.IsClient && BoltNetwork.Server != null)
            {
                BoltLog.Info("Send action! Client at {0}", now);

                var info = string.Format("Client {0} says: {1}", ID, now);
                var data = Encoding.UTF8.GetBytes(info);

                BoltNetwork.Server.SendData(data);
            }

            if (BoltNetwork.IsServer && BoltNetwork.Clients.Any())
            {
                BoltLog.Info("Send action! Server at {0}", now);

                var info = string.Format("Server says: {0}", now);
                var data = Encoding.UTF8.GetBytes(info);

                foreach (var conn in BoltNetwork.Clients)
                {
                    conn.SendData(data);
                }
            }
        }
示例#3
0
        // Bolt Events

        public override void SceneLoadLocalDone(string scene, IProtocolToken token)
        {
            if (scene.Equals("PhotonLobby") && sceneFlag == false)
            {
                return;
            }

            BoltLog.Info(string.Format("New scene: {0}", scene));

            try
            {
                if (lobbyScene.SimpleSceneName == scene)
                {
                    ChangeBodyTo(uiMainMenu);

                    uiTopPanel.HideBackButton();
                    uiTopPanel.SetInGame(false);
                    sceneFlag = true;
                }
                else
                {
                    ChangeBodyTo(null);

                    uiTopPanel.SetInGame(true);
                    uiTopPanel.ToggleVisibility(false);
                    uiTopPanel.SetupBackButton("Menu", ShutdownEventHandler);
                    sceneFlag = false;
                }
            } catch (Exception e)
            {
                BoltLog.Error(e);
            }
        }
        public void SetupPlayer()
        {
            BoltLog.Info("SetupPlayer");

            LobbyPlayerList._instance.AddPlayer(this);
            localPlayer = this;

            nameInput.interactable = true;
            remoteIcone.gameObject.SetActive(false);
            localIcone.gameObject.SetActive(true);

            removePlayerButton.gameObject.SetActive(false);
            removePlayerButton.interactable = false;

            ChangeReadyButtonColor(JoinColor);

            readyButton.transform.GetChild(0).GetComponent <Text>().text = "JOIN";
            readyButton.interactable = true;

            //we switch from simple name display to name input
            colorButton.interactable = true;
            nameInput.interactable   = true;

            nameInput.onEndEdit.RemoveAllListeners();
            nameInput.onEndEdit.AddListener(OnNameChanged);

            colorButton.onClick.RemoveAllListeners();
            colorButton.onClick.AddListener(OnColorClicked);

            readyButton.onClick.RemoveAllListeners();
            readyButton.onClick.AddListener(OnReadyClicked);

            OnClientReady(state.Ready);
        }
        public override void Connected(BoltConnection connection)
        {
            BoltLog.Warn("Connected");

            ServerAcceptToken acceptToken = connection.AcceptToken as ServerAcceptToken;

            if (acceptToken != null)
            {
                BoltLog.Info("AcceptToken: " + acceptToken.GetType());
                BoltLog.Info("AcceptToken: " + acceptToken.data);
            }
            else
            {
                BoltLog.Warn("AcceptToken is NULL");
            }

            ServerConnectToken connectToken = connection.ConnectToken as ServerConnectToken;

            if (connectToken != null)
            {
                BoltLog.Info("ConnectToken: " + connectToken.GetType());
                BoltLog.Info("ConnectToken: " + connectToken.data);
            }
            else
            {
                BoltLog.Warn("ConnectToken is NULL");
            }
        }
示例#6
0
        public override void BoltStartDone()
        {
            if (BoltNetwork.IsServer)
            {
                var token = new RoomProtocolToken()
                {
                    ArbitraryData = "My DATA",
                };

                BoltLog.Info("Starting Server");

                // Start Photon Room
                BoltMatchmaking.CreateSession(
                    sessionID: matchName,
                    token: token
                    );
            }
            else if (BoltNetwork.IsClient)
            {
                if (randomJoin)
                {
                    BoltMatchmaking.JoinRandomSession();
                }
                else
                {
                    ClientStaredUIHandler();
                }

                randomJoin = false;
            }
        }
        public override void Attached()
        {
            if (entity.isOwner)
            {
                state.tokenTest = new TestToken()
                {
                    Number = 1337
                };
            }

            state.AddCallback("tokenTest", () =>
            {
                BoltLog.Info("Received token in .tokenTest property {0}", state.tokenTest);
            });

            state.SetTransforms(state.transform, transform);
            state.SetAnimator(GetComponentInChildren <Animator>());

            // setting layerweights
            state.Animator.SetLayerWeight(0, 1);
            state.Animator.SetLayerWeight(1, 1);

            state.OnFire += OnFire;
            state.AddCallback("weapon", WeaponChanged);

            // setup weapon
            WeaponChanged();
        }
示例#8
0
        /// <summary>
        /// It will perform all necessary steps to serialize and save all configs from the entities on the current project
        /// </summary>
        private static void Save()
        {
            var prefabList = GetPrefabListFromBolt();

            if (prefabList != null && prefabList.Count != 0)
            {
                var updateList = new List <UpdateItem>();

                foreach (var prefabID in prefabList)
                {
                    var go = PrefabDatabase.Find(prefabID);

                    if (go != null)
                    {
                        var updateItem = BuildUpdateItem(go);
                        if (updateItem != null)
                        {
                            updateList.Add(updateItem);
                        }
                    }
                }

                JsonSerializerUpdateUtils.SaveData(updateList, SerializedDataPath);

                BoltLog.Info("Save DONE!");
            }
            else
            {
                BoltLog.Warn("No prefabs found to be serialized");
            }
        }
    private void OnGUI()
    {
        if (ready && BoltNetwork.IsClient)
        {
            GUILayout.BeginVertical(GUILayout.Width(Screen.width), GUILayout.Height(Screen.height));
            {
                GUILayout.BeginHorizontal(GUILayout.Width(Screen.width));
                {
                    size = (int)GUILayout.HorizontalSlider(size, 1, 5000);
                    GUILayout.Label(size.ToString());
                }
                GUILayout.EndHorizontal();

                if (GUILayout.Button("Send data", GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)))
                {
                    if (canSend)
                    {
                        canSend = false;
                        GenerateData();

                        BoltLog.Info("Sending data with hash {0}...", hash);
                        BoltNetwork.Server.StreamBytes(testChannel, data);
                    }
                    else
                    {
                        BoltLog.Info("Waiting data transfer...");
                    }
                }
            }
            GUILayout.EndVertical();
        }
    }
 public override void PacketReceived(UdpPacket udpPacket)
 {
     try
     {
         using (Packet packet = PacketPool.Acquire())
         {
             packet.UdpPacket = udpPacket;
             packet.Frame     = packet.UdpPacket.ReadIntVB();
             if (packet.Frame > this._remoteFrameActual)
             {
                 this._remoteFrameAdjust = true;
                 this._remoteFrameActual = packet.Frame;
             }
             this._bitsSecondInAcc += packet.UdpPacket.Size;
             this._packetsReceived++;
             for (int i = 0; i < this._channels.Length; i++)
             {
                 this._channels[i].Read(packet);
             }
             this._packetStatsIn.Enqueue(packet.Stats);
         }
     }
     catch (Exception exception)
     {
         BoltLog.Exception(exception);
         ModAPI.Log.Write(exception.ToString());
     }
 }
示例#11
0
        /// <summary>
        /// It will perform all steps to load the serialized data on re-config the entities on the project
        /// </summary>
        private static void Load()
        {
            var result = JsonSerializerUpdateUtils.LoadData(SerializedDataPath);

            if (result != null)
            {
                var prefabList = GetPrefabListFromProject();

                foreach (var prefab in prefabList)
                {
                    foreach (var updateItem in result)
                    {
                        if (prefab.name.Equals(updateItem.name))
                        {
                            UpdateBoltEntity(prefab, updateItem);
                        }
                    }
                }

                BoltLog.Info("Load DONE!");
            }
            else
            {
                BoltLog.Error("Unable to load data");
            }
        }
示例#12
0
    /// <summary>
    /// After scene is loaded, creates the Client Player, this player type will be different from the server player
    /// </summary>
    /// <param name="scene"></param>
    /// <param name="token"></param>
    public override void SceneLoadLocalDone(string scene, IProtocolToken token)
    {
        var serverPlayerToken = token as IntBoltToken;
        int playerType        = 2;

        if (serverPlayerToken == null)
        {
            BoltLog.Warn("Null SceneLoadLocalDone token received");
        }
        else
        {
            playerType = serverPlayerToken.intVal;
        }

        var        spawnPosition = Vector3.zero;
        GameObject spawnPoint;

        BoltLog.Warn($"{this} Client | playerType: " + playerType);

        //playerType is the type of the server player, the client gets the other one
        //Example: if Server Player get the Morgue(type 2), Client will get the Cell (type 1)
        if (playerType == 1)
        {
            //Instantiate player at Morgue
            spawnPoint = GameObject.Find("SpawnPoint Morgue");
        }
        else
        {
            //Instantiate player at Cell
            spawnPoint = GameObject.Find("SpawnPoint Cell");
        }

        var clientPlayer = InstantiatePlayerAtSpawnPoint(spawnPoint);
    }
示例#13
0
    IEnumerator Start()
    {
        var systems = GetComponentsInChildren <ParticleSystem>();

        // find out the maximum lifetime of any particles in this effect
        foreach (var system in systems)
        {
            maxLifetime = Mathf.Max(system.main.startLifetimeMultiplier, maxLifetime);
        }

        // wait for random duration

        float stopTime = Time.time + Random.Range(minDuration, maxDuration);

        while (Time.time < stopTime || earlyStop)
        {
            yield return(null);
        }
        BoltLog.Info("stopping " + name);

        // turn off emission
        foreach (var system in systems)
        {
            ParticleSystem.EmissionModule em = system.emission;
            em.enabled = false;
        }
        BroadcastMessage("Extinguish", SendMessageOptions.DontRequireReceiver);

        // wait for any remaining particles to expire
        yield return(new WaitForSeconds(maxLifetime));

        Destroy(gameObject);
    }
 static void NatUtility_ClosePort(NatDeviceState device, int port)
 {
     lock (syncLock) {
         Mapping mapping = new Mapping(Protocol.Udp, port, port);
         device.Nat.BeginDeletePortMap(mapping, ar => {
             lock (syncLock) {
                 try {
                     device.Nat.EndDeletePortMap(ar);
                     ClosePortMapping(device, port);
                 }
                 catch (MappingException exn) {
                     if (exn.ErrorCode == 714)
                     {
                         ClosePortMapping(device, port);
                     }
                     else
                     {
                         BoltLog.Exception(exn);
                     }
                 }
                 catch (Exception exn) {
                     BoltLog.Exception(exn);
                 }
             }
         }, null);
     }
 }
示例#15
0
    void ChangeState(ConnectState state)
    {
        BoltLog.Info("Changing Connect State: {0} => {1}", _connectState, state);

        // update
        _connectState = state;
    }
        /// <summary>
        /// This custom implementation of the Speaker Factory is very similar to the orignal,
        /// but besides the Speaker instance creation, also stores the reference on the Speaker Registry
        /// for a later use by the players
        ///
        /// <seealso cref="Photon.Voice.Unity.VoiceConnection.SimpleSpeakerFactory"/>
        /// </summary>
        /// <param name="playerId">LoadBalancingClient Player ID</param>
        /// <param name="voiceId">Voice ID</param>
        /// <param name="userData">Custom User Data</param>
        /// <returns>New Speaker instance</returns>
        protected Speaker CustomBoltSpeakerFactory(int playerId, byte voiceId, object userData)
        {
            BoltLog.Info("[BoltVoiceBridge] SpeakerFactory for Player {0}", playerId);

            // Store on the Registry based on the Player ID
            Speaker speaker;
            BoltVoiceSpeakerController oldSpeaker;

            if (speakerRegistry.TryGetValue(playerId, out oldSpeaker))
            {
                speaker = oldSpeaker.gameObject.GetComponent <Speaker>();
            }
            else
            {
                // Create Instance based on the Custom Speker from Bolt
                var speakerInstance = Instantiate(BoltSpeakerPrefab);

                // Get Speaker referecence
                speaker = speakerInstance.GetComponent <Speaker>();

                // Store the player ID on our custom BoltVoiceSpeakerController
                var speakerController = speakerInstance.GetComponent <BoltVoiceSpeakerController>();
                speakerController.PlayerID = playerId;

                speakerRegistry.Add(playerId, speakerController);
            }

            // Return the Speaker reference
            return(speaker);
        }
示例#17
0
    static public List <STuple <BoltGlobalBehaviourAttribute, Type> > GetGlobalBehaviourTypes()
    {
#if UNITY_WSA
        Assembly asm = typeof(BoltLauncher).GetTypeInfo().Assembly;
#else
        Assembly asm = Assembly.GetExecutingAssembly();
#endif

        List <STuple <BoltGlobalBehaviourAttribute, Type> > result = new List <STuple <BoltGlobalBehaviourAttribute, Type> >();

        try
        {
            foreach (Type type in asm.GetTypes())
            {
                if (typeof(MonoBehaviour).IsAssignableFrom(type))
                {
#if UNITY_WSA
                    var attrs = (BoltGlobalBehaviourAttribute[])type.GetTypeInfo().GetCustomAttributes(typeof(BoltGlobalBehaviourAttribute), false);
#else
                    var attrs = (BoltGlobalBehaviourAttribute[])type.GetCustomAttributes(typeof(BoltGlobalBehaviourAttribute), false);
#endif
                    if (attrs.Length == 1)
                    {
                        result.Add(new STuple <BoltGlobalBehaviourAttribute, Type>(attrs[0], type));
                    }
                }
            }
        }
        catch (Exception e)
        {
            BoltLog.Exception(e);
        }

        return(result);
    }
        public void OnJoinedRoom()
        {
            BoltLog.Info("[BoltVoiceBridge] Joined Room as Player {0}", LocalPlayerID);

            // Reset the Group to the default group
            ResetVoiceGroup();
        }
示例#19
0
        public override void BoltStartDone()
        {
            if (!BoltNetwork.isRunning)
            {
                return;
            }

            if (BoltNetwork.isServer)
            {
                RoomProtocolToken token = new RoomProtocolToken()
                {
                    ArbitraryData = "My DATA",
                };

                BoltLog.Info("Starting Server");
                // Start Photon Room
                BoltNetwork.SetServerInfo(_matchName, token);

                // Setup Host
                infoPanel.gameObject.SetActive(false);
                ChangeTo(lobbyPanel);

                backDelegate = Stop;
                SetServerInfo("Host", "");

                // Build Server Entity
                //BoltEntity entity = BoltNetwork.Instantiate(BoltPrefabs.PlayerInfo);
                //entity.TakeControl();
            }
            else if (BoltNetwork.isClient)
            {
                backDelegate = Stop;
                SetServerInfo("Client", "");
            }
        }
    public void ReceiveInput(string val)
    {
        if (_stopReceiveInput)
        {
            return;
        }

        var tempVal = _storedVal + val;

        if (tempVal.Length <= maxChars)
        {
            _storedVal = tempVal;

            //Trigger val added
            notifyValAdded?.Invoke(val);
            notifyVal?.Invoke(_storedVal);
        }

        if (_storedVal.Length == maxChars)
        {
            BoltLog.Warn($"{this} filled triggered | val: {_storedVal}");

            _stopReceiveInput = true;
            notifyFilled?.Invoke(_storedVal);
        }
    }
示例#21
0
    private static void Clean()
    {
        try
        {
            BoltLog.Info("Start Cleaning!");

            var step  = 1;
            var total = _packets.Count;

            foreach (var packet in _packets)
            {
                BoltLog.Info("Packaging {0}/{1}: {2}", step++, total, packet.Path);

                packet.Delete();

                                #if BOLT_CLOUD
                if (packet.IsPro)
                {
                    packet.DeletePacket();
                }
                                #endif
            }

            _extra.Delete();

            BoltLog.Info("Packaging DONE!");
        }
        finally
        {
            AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
        }
    }
        // Use this for initialization
        void Start()
        {
            // Get custom arguments from command line
            Map      = GetArg("-m", "-map") ?? Map;
            GameType = GetArg("-t", "-gameType") ?? GameType; // ex: get game type from command line
            RoomID   = GetArg("-r", "-room") ?? RoomID;

            // Validate the requested Level
            var validMap = false;

            foreach (string value in BoltScenes.AllScenes)
            {
                if (SceneManager.GetActiveScene().name != value)
                {
                    if (Map == value)
                    {
                        validMap = true;
                        break;
                    }
                }
            }

            if (!validMap)
            {
                BoltLog.Error("Invalid configuration: please verify level name");
                Application.Quit();
            }

            // Start the Server
            BoltLauncher.StartServer();
            DontDestroyOnLoad(this);
        }
        public override void ControlGained()
        {
            BoltLog.Info("ControlGained");

            readyButton.transform.GetChild(0).GetComponent <Text>().color = Color.white;
            SetupPlayer();
        }
示例#24
0
        // ======= PRIVATE METHODS =====================================================================================

        public static int FindMissingComponents()
        {
            int missingScriptsCount     = 0;
            List <Component> components = new List <Component>();

            var folders = new string[] { "Assets" };
            var iter    = AssetDatabase.FindAssets("t:Prefab", folders).GetEnumerator();

            while (iter.MoveNext())
            {
                var guid = (string)iter.Current;
                var path = AssetDatabase.GUIDToAssetPath(guid);
                var go   = AssetDatabase.LoadAssetAtPath <GameObject>(path);

                go.GetComponentsInChildren(true, components);
                for (int j = 0; j < components.Count; ++j)
                {
                    if (components[j] == null)
                    {
                        ++missingScriptsCount;
                        BoltLog.Error("Missing script: " + path);
                    }
                }
                components.Clear();
            }

            if (missingScriptsCount != 0)
            {
                BoltLog.Info("Found {0} Missing Scripts", missingScriptsCount);
            }

            return(missingScriptsCount);
        }
        public override void ConnectRequest(UdpEndPoint endpoint, IProtocolToken token)
        {
            BoltLog.Warn("Connect Request");

            //token should be ServerConnectToken
            if (token != null)
            {
                BoltLog.Warn(token.GetType().ToString());

                ServerConnectToken t = token as ServerConnectToken;
                BoltLog.Warn("Server Token: null? " + (t == null));
                BoltLog.Warn("Data: " + t.data);
            }
            else
            {
                BoltLog.Warn("Received token is null");
            }

            ServerAcceptToken acceptToken = new ServerAcceptToken
            {
                data = "Accepted"
            };

            BoltNetwork.Accept(endpoint, acceptToken);
        }
示例#26
0
        public override void SessionListUpdated(Map <Guid, UdpSession> sessionList)
        {
            if (_timerRoutine != null)
            {
                StopCoroutine(_timerRoutine);
                _timerRoutine = null;
            }

            Debug.LogFormat("Session list updated: {0} total sessions", sessionList.Count);

            foreach (var session in sessionList)
            {
                PhotonSession photonSession = session.Value as PhotonSession;

                if (photonSession != null && photonSession.Source == UdpSessionSource.Photon)
                {
                    object value;
                    if (photonSession.Properties.TryGetValue("type", out value))
                    {
                        BoltLog.Info("Room with type: {0}", value);
                    }

                    if (photonSession.Properties.TryGetValue("map", out value))
                    {
                        BoltLog.Info("Room with map: {0}", value);
                    }

                    BoltMatchmaking.JoinSession(photonSession);
                }
            }
        }
示例#27
0
        private bool BuildBindingInfo(out BindingInfo bindingInfo)
        {
            var connectionInfo = PlayFabMultiplayerAgentAPI.GetGameServerConnectionInfo();

            IPAddress address;

            if (IPAddress.TryParse(connectionInfo.PublicIpV4Adress, out address))
            {
                try
                {
                    var portInfo   = connectionInfo.GamePortsConfiguration.First(port => port.Name.Equals(BindingConfigKey));
                    var externalIP = new IPEndPoint(address, portInfo.ClientConnectionPort);

                    bindingInfo = new BindingInfo
                    {
                        externalInfo       = externalIP,
                        internalServerPort = portInfo.ServerListeningPort
                    };

                    return(true);
                }
                catch (InvalidOperationException ex)
                {
                    BoltLog.Exception(ex);
                }
            }

            bindingInfo = null;
            return(false);
        }
示例#28
0
        // Utils

        private static IEnumerator ShutdownAndStartServer(int timeout = 10)
        {
            yield return(new WaitForSeconds(timeout));

            BoltLog.Warn("No server found, restarting");
            BoltNetwork.ShutdownImmediate();
        }
示例#29
0
    public override void SceneLoadLocalDone(string scene, IProtocolToken token)
    {
        var serverPlayerToken = token as IntBoltToken;
        int playerType        = 1;

        if (serverPlayerToken == null)
        {
            BoltLog.Warn("Null SceneLoadLocalDone token received");
        }
        else
        {
            playerType = serverPlayerToken.intVal;
        }

        var        spawnPosition = Vector3.zero;
        var        spawnRotation = Quaternion.identity;
        GameObject spawnPoint;

        BoltLog.Warn($"{this} Server | playerType: " + playerType);

        if (playerType == 1)
        {
            //Instantiate player at Cell
            spawnPoint = GameObject.Find("SpawnPoint Cell");
        }
        else
        {
            //Instantiate player at Morgue
            spawnPoint = GameObject.Find("SpawnPoint Morgue");
        }

        //TODO: factory pattern
        var serverPlayer = InstantiatePlayerAtSpawnPoint(spawnPoint);
    }
        static void NatUtility_OpenPort_Finish(NatDeviceState device, int port)
        {
            try {
                var natMapping = device.PortMappings.Values.FirstOrDefault(p => p.Internal == port && p.External == port);
                if (natMapping != null)
                {
                    // set this port as open
                    natMapping.Status = Bolt.NatPortMappingStatus.Open;

                    // tell user about this
                    portChanges.Enqueue(new NatPortMappingChanged {
                        Device = device, Mapping = natMapping.Clone()
                    });

                    // meep
                    BoltLog.Info("Changed {0} on {1}", natMapping, device);
                }
                else
                {
                    BoltLog.Warn("Received incorrect port mapping result from {0}", device);
                }
            }
            catch (Exception exn) {
                BoltLog.Exception(exn);
            }
        }