Badumna Network Suite

Сеть в Unity3D

Badumna Network Suite

Сообщение antonio 09 авг 2010, 13:08

Badumna позволяет создавать многопользовательские приложения от самых простых казуальных игр до сложных AAA класса.
В комплекте есть UnityPackage с демками. Для Indie девелоперов бесплатно.
Для заинтересованных в MMO. http://www.badumna.com/badumna/showcase.html
Аватара пользователя
antonio
UNIт
 
Сообщения: 132
Зарегистрирован: 03 ноя 2009, 15:42
Откуда: Смоленск

Re: Badumna Network Suite

Сообщение Ert Donuell 15 авг 2010, 15:05

Скачал, стал разбираться. Изучил вдоль и поперёк. Изучил мануал. Запускаю демки - ни одна не пашет. Ничего не подключается.
Запускаю DeiMySql, SeedPeer, UnityArbitrator, База Badumna в MySql импортирована - Пишет ошибку логина. Юзаю дефолтный доступ:
User: admin
Password: admin_password

Пробовал подключение через localhost, 127.0.0.1, а также через публичный ip, с условием что всё это запускаю на ноутбуке, подключенном к интернету через роутер. Кто знает в чём дело? Как исправить ситуацию?
Последний раз редактировалось Ert Donuell 23 сен 2010, 19:43, всего редактировалось 1 раз.
Добавить dmitrii.baranov.yumasoft в Skype
Аватара пользователя
Ert Donuell
Старожил
 
Сообщения: 781
Зарегистрирован: 05 июл 2010, 09:50
Откуда: Санкт-Петербург
  • ICQ

Re: Badumna Network Suite

Сообщение Ert Donuell 04 сен 2010, 17:48

Неужели никто не поможет?? :((
Добавить dmitrii.baranov.yumasoft в Skype
Аватара пользователя
Ert Donuell
Старожил
 
Сообщения: 781
Зарегистрирован: 05 июл 2010, 09:50
Откуда: Санкт-Петербург
  • ICQ

Re: Badumna Network Suite

Сообщение DbIMok 04 сен 2010, 19:08

причин, почему не работает, слишком много. почитайте http://forum.unity3d.com/viewtopic.php?t=49422 спросите там же, если не найдете ответ. а без конкретной строки с ошибкой из логов, даже искать непонятно что.
правильный вопрос - половина ответа. учитесь формулировать вопросы понятно.
Новости > _Telegram чат @unity3d_ru (11.6k/4.8k online) > _Telegram канал @unity_news (4.7k подписчиков) > Телеграм тема > "Спасибо"
Аватара пользователя
DbIMok
Адепт
 
Сообщения: 6372
Зарегистрирован: 31 июл 2009, 14:05

Re: Badumna Network Suite

Сообщение Ert Donuell 05 сен 2010, 09:20

Спасибо)
Добавить dmitrii.baranov.yumasoft в Skype
Аватара пользователя
Ert Donuell
Старожил
 
Сообщения: 781
Зарегистрирован: 05 июл 2010, 09:50
Откуда: Санкт-Петербург
  • ICQ

Re: Badumna Network Suite

Сообщение Ert Donuell 19 сен 2010, 21:36

Гружу в таком порядке:

DeiMySql:
Код: Выделить всё
Attempting to read authfile
Getting mysql password from auth file
Using default passphrase for server certificate:
Using default certificate file
Attempting to listen on port 21259
Listening using Ssl connection: True


SeedPeer:
Код: Выделить всё
Success load the dei configuration from deiConfig


UnityArbitrator:
Код: Выделить всё
Success load the dei configuration from deiConfig
Successfully load database configuration from DbConfig
Connection String : Server=localhost;Database=badumna;User ID=root;Password=password;Pooling=false;



Игроки с одной машины не могут подконнектиться. Только у первого отображается чат.
Добавить dmitrii.baranov.yumasoft в Skype
Аватара пользователя
Ert Donuell
Старожил
 
Сообщения: 781
Зарегистрирован: 05 июл 2010, 09:50
Откуда: Санкт-Петербург
  • ICQ

Re: Badumna Network Suite

Сообщение DbIMok 20 сен 2010, 00:37

Ert Donuell писал(а):Игроки с одной машины не могут подконнектиться.

в смысле с этого же localhost?
Ert Donuell писал(а):Только у первого отображается чат.

что при этом в логах у клиента и сервера?
правильный вопрос - половина ответа. учитесь формулировать вопросы понятно.
Новости > _Telegram чат @unity3d_ru (11.6k/4.8k online) > _Telegram канал @unity_news (4.7k подписчиков) > Телеграм тема > "Спасибо"
Аватара пользователя
DbIMok
Адепт
 
Сообщения: 6372
Зарегистрирован: 31 июл 2009, 14:05

Re: Badumna Network Suite

Сообщение Ert Donuell 20 сен 2010, 14:25

да, с того же локального хоста.

У клиента и сервера одна и та же фигня. (запускал скомпилированный проект и эдиторский) - при попытке залогиниться пишет
Код: Выделить всё
Progress 0
UnityEngine.Debug:Log(Object)
GUILoginScript:LoginProgressNotification(LoginStage, String, Int32) (at Assets/Plugins/GUIScript/GUILoginScript.cs:194)
Dei.DeiTokenSupplier:ᜀ(LoginProgressNotification, LoginStage, Int32, String)
Dei.DeiTokenSupplier:ᜀ(Boolean, LoginProgressNotification)
Dei.DeiTokenSupplier:Authenticate(String, String, LoginProgressNotification)
GUILoginScript:DoDeiLogin() (at Assets/Plugins/GUIScript/GUILoginScript.cs:176)
GUILoginScript:DoLogin() (at Assets/Plugins/GUIScript/GUILoginScript.cs:157)

FailedToLogin
UnityEngine.Debug:Log(Object)
GUILoginScript:DoDeiLogin() (at Assets/Plugins/GUIScript/GUILoginScript.cs:185)
GUILoginScript:DoLogin() (at Assets/Plugins/GUIScript/GUILoginScript.cs:157)
GUILoginScript:MakeLoginWindow(Int32) (at Assets/Plugins/GUIScript/GUILoginScript.cs:93)
UnityEngine.GUI:BeginWindows(Event, Int32, IDList, Int32)


и при попытке запуска игры в обход логина (где он должен логиниться автоматически)
Код: Выделить всё
Router model: <unknown>
Public address: Restricted port|xxx.xxx.xx.xx:1440
Private address: Internal|xxx.xxx.x.xxx:4797, Internal|x.xx.xx.xx:4797,
Active connections: 0
Initializing connections: 1

Discovery method: Seed
Last discovery time: Mon, 20 Sep 2010 15:29:50 GMT


Вот код GUILoginScript.cs:
Синтаксис:
Используется csharp
using System;
using System.Collections;

using Dei;          // The authentication library.
using UnityEngine;


/// The GUILoginScript class is used to display the Login GUI,
/// handle the login authentication and load the demo Level if
/// the authentication is successfull.
public class GUILoginScript : MonoBehaviour
{
    public String Username = "";
    public String[] ListOfScenes;

    public String PlayerType;
    public String SceneName;

    public Texture2D ProgressForground;
    public Texture2D ProgressBackground;

    private String mPassword = "";
    private Rect mWindowRect = new Rect((Screen.width / 2 - 100), (Screen.height / 2 - 50), 200, 100);
    private bool mHideLoginWindow = false;
    private bool mIsBusy = false;
    private bool mChooseLevel = false;
    private bool mChoosePlayer = false;
    private float mLoginProgress = 0f;

    private DeiTokenSupplier mTokenSupplier;
    public DeiTokenSupplier TokenSupplier { get { return this.mTokenSupplier; } }

    void OnGUI()
    {
        if (!this.mHideLoginWindow)
        {
            this.mWindowRect.height = 100;
            this.mWindowRect = GUI.Window(0, this.mWindowRect, this.MakeLoginWindow, "Login");
        }

        if (this.mChooseLevel)
        {
            // This is used to customize the height of the window box according to
            // numbers of scenes available in the game
            if (this.ListOfScenes.Length != 0)
            {
                this.mWindowRect.height = 30 * (this.ListOfScenes.Length + 1) + 5;
            }
            else
            {
                this.mWindowRect.height = 125;
            }
            this.mWindowRect = GUI.Window(1, this.mWindowRect, this.MakeLevelChooserWindow, "Choose Demo");
        }

        if (this.mChoosePlayer)
        {
            this.mWindowRect.height = 100;
            this.mWindowRect = GUI.Window(2, this.mWindowRect, this.MakePlayerChooserWindow, "Choose Player");
        }
    }

    void Update()
    {
    }

    // Get the user credentials and perform the login operation
    private void MakeLoginWindow(int id)
    {
        // TODO: modify this code to customize the login box. At present it only provides
        // a minimal login box (i.e. username and password).

        GUILayoutOption[] options = { GUILayout.Width(100), GUILayout.Height(20) };
        GUILayout.BeginHorizontal();
        GUILayout.Label("Username");
        this.Username = GUILayout.TextField(this.Username, options);
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        GUILayout.Label("password");
        this.mPassword = GUILayout.PasswordField(this.mPassword, '*', 25, options);
        GUILayout.EndHorizontal();

        if (this.mIsBusy)
        {
            this.DrawProgress(new Vector2(10, 80), new Vector2(180, 10));
        }
        else
        {
            if (GUILayout.Button("Login"))
            {
                this.mLoginProgress = 0f;
                this.mIsBusy = true;
                this.DoLogin();
            }
        }
    }

    // Choose a level from the available scenes
    private void MakeLevelChooserWindow(int id)
    {
        for (int i = 0; i < this.ListOfScenes.Length; i++)
        {
            if (GUILayout.Button(this.ListOfScenes[i]))
            {
                this.SceneName = this.ListOfScenes[i];
                this.mChoosePlayer = true;
                this.mChooseLevel = false;
            }
        }

        if (GUILayout.Button("Cancel"))
        {
            this.mHideLoginWindow = false;
            this.mChooseLevel = false;
        }
    }

    // This PlayerChooser Menu is designed for Demo1 and Demo2 only where there are
    // two types of character (i.e. MonsterLerpz and SmallLerpz)
    private void MakePlayerChooserWindow(int id)
    {
        if (GUILayout.Button("MonsterLerpz"))
        {
            this.PlayerType = "MonsterLerpz";
            this.EnterScene();
        }

        if (GUILayout.Button("SmallLerpz"))
        {
            this.PlayerType = "SmallLerpz";
            this.EnterScene();
        }

        if (GUILayout.Button("Cancel"))
        {
            this.mChooseLevel = true;
            this.mChoosePlayer = false;
        }
    }

    // Display the login progress bar
    private void DrawProgress(Vector2 location, Vector2 size)
    {
        GUI.DrawTexture(new Rect(location.x, location.y, size.x, size.y), this.ProgressBackground);
        GUI.DrawTexture(new Rect(location.x, location.y, size.x * this.mLoginProgress, size.y), this.ProgressForground);
    }


    private void DoLogin()
    {
        this.mLoginProgress = 1f;
        this.mIsBusy = false;
                // uncomment this when the dei login is not used
        //this.mHideLoginWindow = true;
        //this.mChooseLevel = true;

        this.DoDeiLogin();
    }

    // The version of mono that unity uses does not support ssl streams (required for DEI),
    //
    private void DoDeiLogin()
    {
        // The token supplier is responsible for issuing user certificates, which in turn
        // are used to authenticate users for forming connections and performing other
        // security operations.
        //
        // The Dei token supplier is a cebtralised remote service which can be customised to any
        // backend data base. For more information see http://www.badumna.com/badumna/api
                this.mTokenSupplier = new DeiTokenSupplier("secure.badumna.com", 21259,false);

        // Ignore the ssl errors when running the Dei server on localhost
                // this.mTokenSupplier = new DeiTokenSupplier("172.16.19.77", 21259, false);
                // this.mTokenSupplier.IgnoreSslErrors = true;

        LoginResult result = this.mTokenSupplier.Authenticate(this.Username, this.mPassword, this.LoginProgressNotification);
        if (result.WasSuccessful)
        {
            this.mIsBusy = false;
            this.mHideLoginWindow = true;
            this.mChooseLevel = true;
        }
        else
        {
            Debug.Log("FailedToLogin");
        }
    }

    // This callback method is called periodically by the token supplier during the authentication process.
    // The return value indicates whether to continue with the process or to give up.
    // The description is a human readable (english only at the moment) description of the login stage.
    private bool LoginProgressNotification(LoginStage stage, string description, int percentageComplete)
    {
        Debug.Log("Progress " + percentageComplete.ToString());
        this.mLoginProgress = (float)(percentageComplete / 100);
        return true;
    }

    private void EnterScene()
    {
        Destroy(GameObject.Find("Main Camera"));
        Application.LoadLevelAdditive(this.SceneName);
        this.mChoosePlayer = false;
    }
}
 


Вот NetworkInitialization.cs:
Синтаксис:
Используется csharp
using System;
using System.Collections.Generic;
using System.Text;

using UnityEngine;

using Badumna.DataTypes;
using Badumna.SpatialEntities;
using Badumna;
using Badumna.Arbitration;

using UnityArbitrationEvents;

using Dei;

/// <summary>
/// The NetworkInitialization class is used to initialize the Badumna network library.
/// Configuration options are specified in the constructor.
///
/// The Badumna Network initialization is called in Awake() function (Awake
/// is called when the script instance is loaded, is called only once
/// during the lifetime of the script instance)
///
/// Start is called after Awake function of each script has been called (see
/// Unity ScriptReference help for further information about Start() function)
/// Initiate the localAvatar and register this instance class to current scene
///
/// update the Badumna by calling ProcessNetworkState everytime FixedUpdate
/// function is called (more information about ProcessNetworkState can be seen
/// in http://www.badumna.com/badumna/api/)
/// </summary>
public class NetworkInitialization : MonoBehaviour
{
    public GameObject[] ListOfAvatars;        // List of possible avatar objects

        public Boolean allowChangeLevel = false; // by default is false
    public IArbitrator Arbitrator;
    public GUIScoreScript GUIScore;

    private Dictionary<BadumnaId, RemoteAvatar> mRemoteEntities = new Dictionary<BadumnaId, RemoteAvatar>();

    protected NetworkScene mNetworkScene;
    private string mNetworkSceneName = "Demo6";  //"Unity-Badumna Demo World";
    private LocalAvatar mLocalAvatar;
        private int mLocalAvatarId = 0;
    private Boolean mIsRegistered = false;
        private Boolean mIsChangeLevel = false;

    private DeiTokenSupplier mTokenSupplier;

    /// <summary>
    /// Initializes a new instance of the <see cref="NetworkInitialisation"/> class.
    /// </summary>
    public NetworkInitialization()
    {
        // The configuration options must be specified before a call to NetworkFacade.Instance.Initialize.        
        // By default Badumna will look for a file called 'NetworkConfig.xml' (included in the package)
        // which specifies the configuration options to use.

        // In general it is better to use an xml file for configuration because a re-compilation is not required
        // when experimenting with options, however, the security restrictions for the Unity web player
        // do not allow access to the file system, so we use programatically specified configuration options when
        // the file cannot be read.
        try
        {
            NetworkFacade.ConfigureFrom("NetworkConfig.xml");
        }
        catch (Exception)
        {
            // If the NetworkConfigFile.xml file could not be loaded then we try setting the options programatically
            ConfigurationOptions badumnaConfigOptions = new ConfigurationOptions();

            // The type of discovery mechanism to use.
            // Badumna requires the knowledge of one existing peer to connect with in
            // order to join the network. The address of any other peer can be 'discovered' through
            // two main mechanisms ;
            // - NameServers (a web service dedicated to the recording of recent peers) and
            // - SeedPeers (peers that are 'always' running)
            // If no mechanism is specified then peers can still discovery each other through UDP broadcast,
            // but only when they are on the same local network.
            badumnaConfigOptions.DiscoveryType = DiscoveryType.SeedPeer;

            // The source address of the discovery mechanism.
            // For the NameServer mechanism this specifies the web service's url (eg. http://www.badumna.com/Login/)
            // For the SeedPeer mechanism this is comma seperated list of the public addresses of the seed peers.
            badumnaConfigOptions.DiscoverySource = "secure.badumna.com:21255";

            // The port used for discovery of peers via UDP broadcast.
            // 0 disables the use of broadcast
            badumnaConfigOptions.BroadcastPort = 34524;

            // The arbitration server
            //badumnaConfigOptions.ArbitrationServer = "128.250.76.95:27248";
                        badumnaConfigOptions.ArbitrationServer = "secure.badumna.com:27248";
       
            // For futher configurations operations see https://www.badumna.com/badumna/api/
            NetworkFacade.ConfigureFrom(badumnaConfigOptions);
        }
    }

    #region MonoBehaviour members

    // Three steps to initialize and join a scene in Badumna :
    // Step 1 : Initialize the Network by calling NetworkFacade.Instance.Initialize() (make sure the
    //          network is not initialized already by calling the function NetworkFacade.Instance.IsOnline)
    //
    // Step 2 : If the initialisation process is successful, then Authenticate the user by calling
    //          NetworkFacade.Instance.Login(). The default Login() overload is used only for testing, it DOES NOT
    //          validate user credentials in any way and issues a default commonly known certificate resulting
    //          in a totally unsecure network (any one can join and pretend to be anyone else). For more information
    //          see the api documentation for ITokenSupplied to provide your own authentication service or Dei for
    //          a ready to use service.
    //
    // Step 3 : Ensure that login was successful then join the scene by calling NetworkFacade.
    //          Instance.JoinScene(string SceneName, CreateSpatialReplica createEntityDelegate,
    //          RemoveSpatialReplica removeEntityDelegate)
    //          - createEntityDelegate function will be called when there is remote entity joining the scene
    //            and its position is within the interest sphere radius.
    //          - removeEntityDelegate function will be called when a remote entity
    //            leaves the scene or its position moves outside the interest sphere radius.  
    void Awake()
    {
                DontDestroyOnLoad(this); // Don't Destroy this object when a new level is loaded

        // Check whether the network has been initiated yet
        if (!NetworkFacade.Instance.IsInitialized)
        {
            // Initialize the Badumna network library
            NetworkFacade.Instance.Initialize();

            // Find the gui login script to get the users login and password
            GameObject guiLogin;
            GUILoginScript login;

            if (guiLogin = GameObject.Find("GuiLogin"))
            {
                login = (GUILoginScript)guiLogin.GetComponent(typeof(GUILoginScript));
                this.mNetworkSceneName = login.SceneName; // Record the scene chose by the user
                this.mTokenSupplier = login.TokenSupplier;

                NetworkFacade.Instance.Login(this.mTokenSupplier); // Login to Badumna using token supplier
            }
            else
            {
                NetworkFacade.Instance.Login();
            }
        }

        if (NetworkFacade.Instance.IsLoggedIn)
        {
            // Join the chosen scene.
            // Scenes are identified by a name (a string) which should be unique.
            // All entities within a scene will see each other, but not any entities
            // in other scenes.
            this.mNetworkScene = NetworkFacade.Instance.JoinScene(this.mNetworkSceneName, this.CreateEntity, this.RemoveEntity);
                        Debug.Log(NetworkFacade.Instance.GetNetworkStatus().ToString());
        }
        else
        {
            Debug.LogError("Login error");
            return;
        }

        // Additional code for arbitration server
        this.Arbitrator = NetworkFacade.Instance.GetArbitrator();
        this.Arbitrator.ServerEvent = delegate(byte[] message) { this.HandleArbitrationEvent(message); };
        this.Arbitrator.Connect();
    }

    // Initialise the local avatar/player after the network initialisation processes has completed and then
    // register the local avatar in the current scene by calling
    // NetworkScene.RegisterEntity(ISpatialOriginal entity, uint entityType)
    //
    // Note:  - Awake() function is always called before any Start function in Unity
    //        - See http://www.badumna.com/badumna/api/clas ... scene.html
    //          for more details information regarding RegisterEntity function.
    //
    void Start()
    {
        if (!this.CreateLocalPlayer())
        {
            Debug.LogError("Failed to create local avatar.");
            return;
        }

        this.InitiateChatInterface();
    }

    // NetworkFacade.Instance.ProcessNetworkState() is called everytime the FixedUpdate function
    // is called. ProcessNetworkState performs processing of network events that need to be processed,
    // the application, eg. handling updates and other messages, add/removing entities and processing
    // chat messages. This method must be called regularly to ensure timely processsing of these events.
    //
    // Note : - for more information regarding ProcessNetworkState(), please refer
    //          to http://www.badumna.com/badumna/api/1.3/badumna
    //        - before calling the ProcessNetworkState make sure that the Network is Initialized
    //          successfully. An exception will be thrown otherwise.
    //
    void FixedUpdate()
    {
        if (NetworkFacade.Instance.IsInitialized)
        {
            NetworkFacade.Instance.ProcessNetworkState();
           
            if (mLocalAvatar != null)
            {
                this.ArbitrationEventUpdate();
            }
        }

        // set allowChangeLevel into true when the game have more than one level, and it is possible
        // to change level under certain circumstances
                if(this.allowChangeLevel)
                {
                        UnityEngine.Vector3 position = new UnityEngine.Vector3(this.mLocalAvatar.Position.X,
                                                                        this.mLocalAvatar.Position.Y,this.mLocalAvatar.Position.Z);

                        string nextScene = ChangingScene.changeScene(position, this.mNetworkSceneName);
                        if (!this.mNetworkSceneName.Equals(nextScene))
                        {                      
                                this.mNetworkSceneName = nextScene;
                                this.mIsChangeLevel = true;
                                Application.LoadLevel(nextScene);
                        }
                }
    }

    // this function is called after the level is loaded, in this case we need to register the current
    // local avatar to the corresponding scene
        void OnLevelWasLoaded(int level)
        {
                if(this.mLocalAvatar != null)
                {
                        Debug.Log("Level:" + level);

                        // Check the status of the badumna network before joining a new scene
                        if (!NetworkFacade.Instance.IsInitialized)
                        {
                                NetworkFacade.Instance.Initialize();
                if (this.mTokenSupplier != null)
                {
                    NetworkFacade.Instance.Login(this.mTokenSupplier);
                }
                else
                {
                    NetworkFacade.Instance.Login();
                }
                        }
                        else if (!NetworkFacade.Instance.IsLoggedIn)
                        {
                if (this.mTokenSupplier != null)
                {
                    NetworkFacade.Instance.Login(this.mTokenSupplier);
                }
                else
                {
                    NetworkFacade.Instance.Login();
                }
                        }
                       
                        if(NetworkFacade.Instance.IsLoggedIn)
                        {
                                this.mNetworkScene = NetworkFacade.Instance.JoinScene(this.mNetworkSceneName, this.CreateEntity, this.RemoveEntity);
                        }
                       
            // register local player into current scene
                        uint entityType = (uint)(PlayerType) Enum.Parse(typeof(PlayerType), this.mLocalAvatar.LocalAvatarTag,true);
                        this.mNetworkScene.RegisterEntity(this.mLocalAvatar, entityType);
                        this.mIsRegistered = true;
                        this.mIsChangeLevel = false;

                        Debug.Log(NetworkFacade.Instance.GetNetworkStatus().ToString());
                }
        }
       
    void OnApplicationQuit()
    {
        // Note: OnApplicationQuit is called before the OnDisable function is called on any other behaviours,
        //       therefore, this is a good place to implement any code which is required to be called prior to
        //       individual OnDisable functions.
    }

    // Three steps to unregister the local entity (local player) from the scene and shut down Badumna
    // Step 1: Unregister the local entity by calling NetworkScene.UnregisterEntity(ISpatialOriginal entity).
    //         When this function is called, other peers will receive notification of the entities departure via the
    //         their RemoveEntity method.
    // Step 2: After successfully unregistering the entity call NetworkFacade.Instance.Logout to leave
    //         the network
    // Step 3: Then shutdown the Badumna library by calling the NetworkFacade.Instance.Shutdown()
   
        void OnDisable()
    {
        if (this.mIsRegistered)
        {
            // Send the event message to arbitration server before goes offline
            this.SendEvent(new OfflineEvent());

            this.mNetworkScene.UnregisterEntity(this.mLocalAvatar);
            this.mNetworkScene.Leave();
            this.mIsRegistered = false;
                       
                        // when leave scene, clear the remote entities container
                        this.mRemoteEntities.Clear();
        }

        // call this two functions when exiting not when move to other level
     
        if (NetworkFacade.Instance.IsLoggedIn && !this.mIsChangeLevel)
        {
            NetworkFacade.Instance.Logout();
        }

        if (NetworkFacade.Instance.IsInitialized && !this.mIsChangeLevel)
        {
            NetworkFacade.Instance.Shutdown();
        }
    }

    #endregion

    #region NetworkScene members

    // This function will be called from ProccessNetworkState()
    // when there is another entity nearby, i.e. within the local avatars visible region.
    // It creates a remote entity (i.e. remote avatar) and stores it in the list of remote entities.
    private ISpatialReplica CreateEntity(NetworkScene scene, BadumnaId entityId, uint entityType)
    {
        PlayerType playerType = (PlayerType)entityType;
        GameObject remotePlayerObject = this.FindPlayerObject(playerType.ToString());
        RemoteAvatar remoteAvatar;

        if (remotePlayerObject != null)
        {
            remotePlayerObject.AddComponent(typeof(SyncAnimation));
            remotePlayerObject.AddComponent(typeof(RemoteAvatar));
            remoteAvatar = (RemoteAvatar)remotePlayerObject.GetComponent(typeof(RemoteAvatar));
            if (remoteAvatar != null)
            {
                // The network guid should be set to the given guid
                remoteAvatar.Guid = entityId;

                // Note: Change the keyword if necessary, match with the remote avatars tag
                // in this example, all the remote avatars tagname start with "Remote"
                remoteAvatar.SetAvatarToUse(remotePlayerObject);

                // Add the remote avatar to mRemoteEntities
                this.mRemoteEntities.Add(entityId, remoteAvatar);

                ISpatialReplica spatialReplica = remoteAvatar as ISpatialReplica;

                return spatialReplica;
            }
        }
        return null;
    }

    // RemoveEntity will be called if a remote entity leaves the scene (i.e. when the other
    // peer called UnregisterEntity function).
    private void RemoveEntity(NetworkScene scene, ISpatialReplica replica)
    {
        RemoteAvatar remoteAvatar = (RemoteAvatar)replica;
        if (this.mRemoteEntities.TryGetValue(remoteAvatar.Guid, out remoteAvatar))
        {
            remoteAvatar.DestroyRemoteAvatar();
            this.mRemoteEntities.Remove(remoteAvatar.Guid);
        }
    }

    #endregion

    #region ArbitrationEvent Handler

    private void ArbitrationEventUpdate()
    {
        this.SendArbitrationPosition();
        // TODO: added into event handler
        if (this.mLocalAvatar.ArbitratorManager.QueueClientEvents.Count != 0)
        {
            ClientEvent clientEvent = this.mLocalAvatar.ArbitratorManager.QueueClientEvents.Dequeue();
            this.SendEvent(clientEvent);
        }
    }

    private void HandleArbitrationEvent(byte[] message)
    {
                Debug.Log("Handler is called");
        ServerEvent serverEvent = (ServerEvent)ServerEventSet.Instance.Deserialize(message);
               
                if (serverEvent is ReplyEvent)
        {
            Debug.Log("Reply event is received");
        }

        if (serverEvent is GetPunchEvent)
        {
            // TODO: do something when the avatar get punch
                        Debug.Log("GetHit");
            this.mLocalAvatar.IncomingEvent(serverEvent);
        }

        if (serverEvent is AliveEvent)
        {
            Debug.Log("Back to live");
            this.mLocalAvatar.IncomingEvent(serverEvent);
        }

        if (serverEvent is ScoreEvent)
        {
            Debug.Log("Score: " + ((ScoreEvent)serverEvent).Score);
            if (GUIScore != null)
            {
                GUIScore.TextMessages += "Score: " + ((ScoreEvent)serverEvent).Score + "\n";
            }
        }

        // TODO: do something if there is any event received from the arbitration server
    }

    private void SendEvent(ClientEvent clientEvent)
    {
        this.Arbitrator.SendEvent(ClientEventSet.Instance.Serialize(clientEvent));
    }

    private DateTime mLastSendTime;
    private Badumna.DataTypes.Vector3 mLastPosition;

    private void SendArbitrationPosition()
    {
        DateTime now = DateTime.Now;
        if ((now - this.mLastSendTime).TotalMilliseconds < 200 ||
            this.mLastPosition == this.mLocalAvatar.Position)
        {
            return;
        }

        this.mLastPosition = this.mLocalAvatar.Position;
        this.mLastSendTime = now;
        this.SendEvent(new MoveEvent(this.mLocalAvatar.Position,this.mLocalAvatarId));
    }

    #endregion

    private GameObject FindPlayerObject(string objectTag)
    {
        GameObject existingObject = null;

        for (int i = 0; i < this.ListOfAvatars.Length; i++)
        {
            if (this.ListOfAvatars[i].CompareTag(objectTag))
            {
                existingObject = this.ListOfAvatars[i];
                break;
            }
        }

        if (existingObject != null)
        {
            return (GameObject)GameObject.Instantiate(existingObject, transform.position, transform.rotation);
        }

        Debug.LogWarning(String.Format("Player with tag:{0} is not found", objectTag));
        return null;
    }

    private bool CreateLocalPlayer()
    {
        try
        {
            String playerType = PlayerType.SmallLerpz.ToString();
            String playerName = "SmallLerpz";

            GameObject guiLogin;
            GUILoginScript login;

            if (guiLogin = GameObject.Find("GuiLogin"))
            {
                login = (GUILoginScript)guiLogin.GetComponent(typeof(GUILoginScript));
                playerName = login.Username;
                playerType = login.PlayerType;
            }

            GameObject playerObject = null;
            if (playerType != null)
            {
                playerObject = this.FindPlayerObject(playerType);
                if (playerObject != null)
                {
                    // set all the components required
                    playerObject.AddComponent(typeof(CharacterController));
                    playerObject.AddComponent(typeof(ThirdPersonController));
                    playerObject.AddComponent(typeof(ThirdPersonSimpleAnimation));
                    playerObject.AddComponent(typeof(AnimationHandler));
                    playerObject.AddComponent(typeof(CameraFollowerScript));
                                        playerObject.AddComponent(typeof(ArbitratorManager));
                    playerObject.AddComponent(typeof(LocalAvatar));

                    CharacterController controller = (CharacterController)playerObject.GetComponent(typeof(CharacterController));
                    controller.radius = 0.4f;
                    controller.center = new UnityEngine.Vector3(0, 1.1f, 0);

                    this.mLocalAvatar = (LocalAvatar)playerObject.GetComponent(typeof(LocalAvatar));

                    if (this.mLocalAvatar != null)
                    {
                        // Set the game object used by the local avatar, and give the returned entity
                        // type to the RegisterEntity() method. This type id will be passed to the
                        // CreateEntity() mewthod on remote peers when this avatar's replica is instantiated.
                        uint entityType = this.mLocalAvatar.SetAvatarToUse(playerObject, playerName,this.mLocalAvatarId);
                        if (entityType > 0)
                        {
                            this.mNetworkScene.RegisterEntity(this.mLocalAvatar, entityType);
                            this.mIsRegistered = true;
                            return true;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e);
            return false;
        }

        return false;
    }

    private void InitiateChatInterface()
    {
        GameObject parentObject = (GameObject)transform.gameObject;
        parentObject.AddComponent(typeof(GUIChatScript));
        GUIChatScript chatScript = (GUIChatScript)transform.GetComponent(typeof(GUIChatScript));
        chatScript.LocalAvatar = this.mLocalAvatar;
    }

}
 
Последний раз редактировалось Ert Donuell 31 окт 2010, 12:07, всего редактировалось 1 раз.
Добавить dmitrii.baranov.yumasoft в Skype
Аватара пользователя
Ert Donuell
Старожил
 
Сообщения: 781
Зарегистрирован: 05 июл 2010, 09:50
Откуда: Санкт-Петербург
  • ICQ

Re: Badumna Network Suite

Сообщение DbIMok 21 сен 2010, 16:32

насколько я понимаю ситуацию, ты соединяешься локальным сервером, значит надо указать его и отключить проверку ssl.
а с бадумны, имхо, ничего получить не удастся при любом раскладе, потому что:
Код: Выделить всё
nmap secure.badumna.com -p 21259

Starting Nmap 4.60 ( http://insecure.org ) at 2010-09-21 17:37
Interesting ports on birdsville.ee.unimelb.edu.au (128.250.77.202):
PORT      STATE  SERVICE
21259/tcp closed unknown

Nmap done: 1 IP address (1 host up) scanned in 4.484 seconds

P.S. речь про Dei
правильный вопрос - половина ответа. учитесь формулировать вопросы понятно.
Новости > _Telegram чат @unity3d_ru (11.6k/4.8k online) > _Telegram канал @unity_news (4.7k подписчиков) > Телеграм тема > "Спасибо"
Аватара пользователя
DbIMok
Адепт
 
Сообщения: 6372
Зарегистрирован: 31 июл 2009, 14:05

Re: Badumna Network Suite

Сообщение Ert Donuell 21 сен 2010, 17:45

Хмм.. Пардон, это скрипт по-умолчанию. Его я тоже менял. Сидел летом в заточении 2 недели - по-всякому бадумну вертел. Ставил туда localhost, 127.0.0.1, а также публичный айпи. И не только в скрипте. Ничего не пахало. :((
Будет время - модифицирую скрипты, кину сорцы и логи
Последний раз редактировалось Ert Donuell 23 сен 2010, 19:44, всего редактировалось 1 раз.
Добавить dmitrii.baranov.yumasoft в Skype
Аватара пользователя
Ert Donuell
Старожил
 
Сообщения: 781
Зарегистрирован: 05 июл 2010, 09:50
Откуда: Санкт-Петербург
  • ICQ

Re: Badumna Network Suite

Сообщение DbIMok 22 сен 2010, 12:00

дело не в вертел, а в понимании этих скриптов. что там для чего. скрипты по умолчанию не значит, что они правильные и всегда работающие. это просто шаблон/заготовка, который каждому нужно допилить по вкусу.
правильный вопрос - половина ответа. учитесь формулировать вопросы понятно.
Новости > _Telegram чат @unity3d_ru (11.6k/4.8k online) > _Telegram канал @unity_news (4.7k подписчиков) > Телеграм тема > "Спасибо"
Аватара пользователя
DbIMok
Адепт
 
Сообщения: 6372
Зарегистрирован: 31 июл 2009, 14:05

Re: Badumna Network Suite

Сообщение Ert Donuell 22 сен 2010, 20:37

Ну, собственно, это понятно)) Я подразумевал что заменил ip последовательно на localhost, 127.0.0.1, my_global_ip, а он ничего так и не сделал) по логике, он должен подключаться к моим базам данных (мускул был запущен, базы данных импортированы), а затем через них авторизироваться. но увы :ymhug:
Добавить dmitrii.baranov.yumasoft в Skype
Аватара пользователя
Ert Donuell
Старожил
 
Сообщения: 781
Зарегистрирован: 05 июл 2010, 09:50
Откуда: Санкт-Петербург
  • ICQ

Re: Badumna Network Suite

Сообщение Neodrop 22 сен 2010, 21:01

Реальный локальный IP вводить пробовали? Тот, который вам ваш роутер (или что у вас на подключке) вам выдаёт?
Добавить neodrop в Skype
Изображение
"Спасибо!" нашему порталу, вы сможете сказать ЗДЕСЬ.
Если проблема не решается честно, нужно её обмануть! || Per stupiditas at Astra!
Страх порождает слабость. Бесстрашных поражают пули.
Протратившись на блядях байтах, на битах не экономят.
Аватара пользователя
Neodrop
Админ
 
Сообщения: 8480
Зарегистрирован: 08 окт 2008, 15:42
Откуда: Питер
Skype: neodrop
  • Сайт

Re: Badumna Network Suite

Сообщение Ert Donuell 22 сен 2010, 21:06

не, не пробовал =//
Да и в заточении без роутера сидел. Тупа тет-а-тет с ноутом. Спасибо, попробую)
Добавить dmitrii.baranov.yumasoft в Skype
Аватара пользователя
Ert Donuell
Старожил
 
Сообщения: 781
Зарегистрирован: 05 июл 2010, 09:50
Откуда: Санкт-Петербург
  • ICQ

Re: Badumna Network Suite

Сообщение DbIMok 22 сен 2010, 21:32

Код: Выделить всё
this.mTokenSupplier.IgnoreSslErrors = true;

эту строчку включали? потому как:
The Dei protocol uses the SSL protocl which requires a certificate containing the domain name of the server and signed by a trusted authority. If you wish to ignore the ssl validation erros for testing (for eg. if you are using localhost as the server address) then you can set the IgnoreSSLErrors property on the DeiTokenSupplier to true or provide your own certificate validation method when calling the Authenticate method.

и при локальном подключении убедитесь, что у вас этот порт открыт
для нормальной диагностики замените
Код: Выделить всё
Debug.Log("FailedToLogin");

на
Код: Выделить всё
Debug.Log(result.ErrorDescription);
правильный вопрос - половина ответа. учитесь формулировать вопросы понятно.
Новости > _Telegram чат @unity3d_ru (11.6k/4.8k online) > _Telegram канал @unity_news (4.7k подписчиков) > Телеграм тема > "Спасибо"
Аватара пользователя
DbIMok
Адепт
 
Сообщения: 6372
Зарегистрирован: 31 июл 2009, 14:05

След.

Вернуться в Сеть

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 3