public override void Init()
        {
            itemId        = Guid.NewGuid();
            PickupTracker = ScenePrivate.FindReflective <IPickupTracker>("ItemCollector.PickupTracker").FirstOrDefault();
            if (PickupTracker == null)
            {
                Log.Write(LogLevel.Error, "Pickup Detector couldn't find the master Pickup Tracker.  Make sure it's attached to something in the scene, like the floor.");
                return;
            }

            PickupTracker.RegisterPresence(itemId);

            RigidBodyComponent RigidBody;

            if (ObjectPrivate.TryGetFirstComponent(out RigidBody))
            {
                RigidBody.Subscribe(CollisionEventType.CharacterContact, OnPickup);
            }
            else
            {
                Log.Write(LogLevel.Error, "Pickup Detector couldn't find a RigidBody component.  That component is needed in order to detect when an avatar walks into them");
                return;
            }
        }
Beispiel #2
0
        // Init() is where the script is setup and is run when the script starts.
        public override void Init()
        {
            foreach (var rb in Objects)
            {
                if (rb == null)
                {
                    continue;
                }

                ObjectPrivate op = ScenePrivate.FindObject(rb.ComponentId.ObjectId);
                if (op != null)
                {
                    var scripts = op.LookupScripts();
                    AllObjects.Add(op.ObjectId, scripts == null ? 0 : scripts.Length);
                }
            }

            if (MemoryWatch)
            {
                Memory.Subscribe(MemoryUpdate);
            }

            Timer.Create(60, 60, Check);
        }
Beispiel #3
0
        private void Subscribe(ScriptEventData sed)
        {
            if (subscription == null)
            {
                subscription = SubscribeToAll(PlayEvent, (ScriptEventData data) =>
                {
                    try
                    {
                        if (AllowInVR || !ScenePrivate.FindAgent(data.Data.AsInterface <ISimpleData>().AgentInfo.SessionId).Client.InVrAndHandsActive)
                        {
                            CharacterComponent cc;
                            ScenePrivate.FindObject(data.Data.AsInterface <ISimpleData>().AgentInfo.ObjectId).TryGetFirstComponent(out cc);
                            if (cc != null)
                            {
                                cc.PlayAnimation(Animation, (Repeat ? AnimationPlaybackMode.Loop : AnimationPlaybackMode.PlayOnce), (UpperBodyOnly ? AnimationBoneSubset.Subset1 : AnimationBoneSubset.Full), AnimationSpeed);
                            }
                        }
                    }
                    catch {}
                });

                subscription += SubscribeToAll(StopEvent, (ScriptEventData data) =>
                {
                    try
                    {
                        CharacterComponent cc;
                        ScenePrivate.FindObject(data.Data.AsInterface <ISimpleData>().AgentInfo.ObjectId).TryGetFirstComponent(out cc);
                        if (cc != null)
                        {
                            cc.StopAnimations();
                        }
                    }
                    catch {}
                });
            }
        }
Beispiel #4
0
        void OnPickup(HeldObjectData data)
        {
            try
            {
                AgentPrivate agent = ScenePrivate.FindAgent(data.HeldObjectInfo.SessionId);

                holdingAgent         = agent.AgentInfo;
                heldHand             = data.HeldObjectInfo.ControlPoint;
                simpleData.AgentInfo = holdingAgent;
                simpleData.ObjectId  = holdingAgent.ObjectId;
                ammo         = ClipSize;
                shotsFired   = 0;
                shotsHit     = 0;
                score        = 0;
                unsubscribe += agent.Client.SubscribeToCommand(ShootCommand, OnTrigger, null).Unsubscribe;
                unsubscribe += agent.Client.SubscribeToCommand(ReloadCommand, Reload, null).Unsubscribe;
            }
            catch (System.Exception)
            {
                holdingAgent         = null;
                simpleData.AgentInfo = null;
                simpleData.ObjectId  = ObjectId.Invalid;
            }
        }
Beispiel #5
0
        void OnChat(ChatData data)
        {
            if (!enabled)
            {
                return;
            }

            // If this chat message is a relevant command
            if (commands.ContainsKey(data.Message))
            {
                var agent = ScenePrivate.FindAgent(data.SourceId);

                if (IsAccessAllowed(agent))
                {
                    SimpleData sd = new SimpleData(this);
                    sd.SourceObjectId = ObjectPrivate.ObjectId;
                    sd.AgentInfo      = agent?.AgentInfo;
                    if (sd.AgentInfo != null)
                    {
                        sd.ObjectId = sd.AgentInfo.ObjectId;
                    }

                    SendToAll(commands[data.Message], sd);
                }
            }
            // Else if it is the help command (and help not overridden by creator)
            else if (IsHelpCommand(data.Message) && (commands.Keys.Count > 0))
            {
                var agent = ScenePrivate.FindAgent(data.SourceId);

                if (IsAccessAllowed(agent) && (agent != null))
                {
                    agent.SendChat(GetHelpText());
                }
            }
        }
Beispiel #6
0
        void CollectedHint(Objective objective, int collectedSoFar)
        {
            try
            {
                string hint = null;
                if (objective.Definition.RequiredCount <= 1)
                {
                    hint = $"Completed: {objective.Definition.Title}";
                }
                else
                {
                    hint = $"[{collectedSoFar}/{objective.Definition.RequiredCount}] {objective.Definition.Title}";
                }

                AgentPrivate agent = ScenePrivate.FindAgent(objective.Agent);
                agent.Client.UI.HintText = hint;
                Wait(2);
                if (agent.Client.UI.HintText == hint)
                {
                    agent.Client.UI.HintText = "";
                }
            }
            catch (Exception) { }
        }
Beispiel #7
0
        void OnCommand(CommandData data)
        {
            if (!Enabled)
            {
                return;
            }

            CommandFlag currentHotkey = flagFromString(data.Command);

            if (currentHotkey == CommandFlag.Invalid)
            {
                return;
            }

            if (data.Action == CommandAction.Pressed)
            {
                if ((currentHotkey & HeldKeys[data.SessionId]) == 0x0)
                {
                    string sendEvents;
                    if (CommandEvents.TryGetValue(currentHotkey, out sendEvents))
                    {
                        SimpleData sd = new SimpleData(this);
                        sd.SourceObjectId = ObjectPrivate.ObjectId;
                        sd.AgentInfo      = ScenePrivate.FindAgent(data.SessionId)?.AgentInfo;
                        sd.ObjectId       = (sd.AgentInfo != null) ? sd.AgentInfo.ObjectId : ObjectId.Invalid;
                        SendToAll(sendEvents, sd);
                    }

                    HeldKeys[data.SessionId] |= currentHotkey;

                    // If holding more keys, look for the key combo
                    if (HeldKeys[data.SessionId] != currentHotkey &&
                        CommandEvents.TryGetValue(HeldKeys[data.SessionId], out sendEvents))
                    {
                        SimpleData sd = new SimpleData(this);
                        sd.SourceObjectId = ObjectPrivate.ObjectId;
                        sd.AgentInfo      = ScenePrivate.FindAgent(data.SessionId)?.AgentInfo;
                        sd.ObjectId       = (sd.AgentInfo != null) ? sd.AgentInfo.ObjectId : ObjectId.Invalid;
                        SendToAll(sendEvents, sd);
                    }
                }
            }
            else if (data.Action == CommandAction.Released)
            {
                if ((currentHotkey & HeldKeys[data.SessionId]) != 0x0)
                {
                    string sendEvents;

                    // Check for key combo release
                    if (currentHotkey != HeldKeys[data.SessionId] &&
                        CommandReleaseEvents.TryGetValue(HeldKeys[data.SessionId], out sendEvents))
                    {
                        SimpleData sd = new SimpleData(this);
                        sd.SourceObjectId = ObjectPrivate.ObjectId;
                        sd.AgentInfo      = ScenePrivate.FindAgent(data.SessionId)?.AgentInfo;
                        sd.ObjectId       = (sd.AgentInfo != null) ? sd.AgentInfo.ObjectId : ObjectId.Invalid;
                        SendToAll(sendEvents, sd);
                    }

                    HeldKeys[data.SessionId] &= ~currentHotkey;

                    if (CommandReleaseEvents.TryGetValue(currentHotkey, out sendEvents))
                    {
                        SimpleData sd = new SimpleData(this);
                        sd.SourceObjectId = ObjectPrivate.ObjectId;
                        sd.AgentInfo      = ScenePrivate.FindAgent(data.SessionId)?.AgentInfo;
                        sd.ObjectId       = (sd.AgentInfo != null) ? sd.AgentInfo.ObjectId : ObjectId.Invalid;
                        SendToAll(sendEvents, sd);
                    }
                }
            }
        }
Beispiel #8
0
    private void GetSampleInfo(string controlSurface, InteractionData idata)
    {
        string row       = controlSurface.Substring(0, 2);
        string chartest  = controlSurface.Substring(0, 1);
        int    intColumn = 99;

        //Log.Write("row: " + row);
        if (chartest == "R")
        {
            intColumn = Int32.Parse(controlSurface.Substring(3, 1)) - 1;
            //Log.Write("intColumn: " + intColumn);
        }
        if (chartest == "T")
        {
            //Log.Write("In Track Test");
            TrackSelected = true;
            //Log.Write("Selected Track: " + controlSurface.Substring(1, 1));
            SelectedTrackIn = controlSurface.Substring(1, 1);
            sendSimpleMessage("SelectTrackDown", idata);
            if (SelectedSampleName != null)
            {
                //Log.Write("Sending Track Active Message");
                //Log.Write("SelectedTrackIn: " + SelectedTrackIn);
                if (SelectedTrackIn == "1")
                {
                    sendSimpleMessage("Track1On", idata);
                }
                else if (SelectedTrackIn == "2")
                {
                    sendSimpleMessage("Track2On", idata);
                }
                else if (SelectedTrackIn == "3")
                {
                    sendSimpleMessage("Track3On", idata);
                }
                else if (SelectedTrackIn == "4")
                {
                    sendSimpleMessage("Track4On", idata);
                }
                else if (SelectedTrackIn == "5")
                {
                    sendSimpleMessage("Track5On", idata);
                }
                else if (SelectedTrackIn == "6")
                {
                    sendSimpleMessage("Track6On", idata);
                }
                else if (SelectedTrackIn == "7")
                {
                    sendSimpleMessage("Track7On", idata);
                }
                else if (SelectedTrackIn == "8")
                {
                    sendSimpleMessage("Track8On", idata);
                }
                else if (SelectedTrackIn == "9")
                {
                    sendSimpleMessage("Track9On", idata);
                }
            }
        }
        else if (row == "R1")
        {
            SelectedSampleName    = R1SampleNames[intColumn];
            SelectedSoundResource = R1SoundResources[intColumn];
            sendSimpleMessage("SelectTrackUp", idata);
        }
        else if (row == "R2")
        {
            SelectedSampleName    = R2SampleNames[intColumn];
            SelectedSoundResource = R2SoundResources[intColumn];
            sendSimpleMessage("SelectTrackUp", idata);
        }
        else if (row == "R3")
        {
            SelectedSampleName    = R3SampleNames[intColumn];
            SelectedSoundResource = R3SoundResources[intColumn];
            sendSimpleMessage("SelectTrackUp", idata);
        }
        else if (row == "R4")
        {
            SelectedSampleName    = R4SampleNames[intColumn];
            SelectedSoundResource = R4SoundResources[intColumn];
            sendSimpleMessage("SelectTrackUp", idata);
        }
        else if (row == "R5")
        {
            SelectedSampleName    = R5SampleNames[intColumn];
            SelectedSoundResource = R5SoundResources[intColumn];
            sendSimpleMessage("SelectTrackUp", idata);
        }
        else if (controlSurface != null)
        {
            sendSimpleMessage(controlSurface, idata);                               //Change Sample Pack
        }
        if ((TrackSelected) && (SelectedSampleName != null))
        {
            Jammer = ScenePrivate.FindAgent(idata.AgentId)?.AgentInfo;
            SendSampleInfoSelected(SelectedSampleName, SelectedSoundResource, DefaultPan, SelectedTrackIn, Jammer);

            SelectedSampleName    = null;
            SelectedSoundResource = null;
            SelectedTrackIn       = null;
            TrackSelected         = false;
            //sendSimpleMessage("PlaySample", SelectedSampleName, SelectedSoundResource, SelectedTrackIn, idata);
        }
    }
Beispiel #9
0
        void OnTrigger(CommandData command)
        {
            if (command.ControlPoint == ControlPointType.DesktopGrab)
            {
                if (!FreeClickEnabled && !command.MouseLookMode)
                {
                    AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                    user.SendChat("This device does not work in desktop Free Click Mode: press Escape to enter or exit Mouse Look.");
                    return;
                }
            }

            try
            {
                if (CheckReload(command))
                {
                    return;
                }

                if (command.ControlPoint != heldHand)
                {
                    // Let them use the off hand to reload the gun, but otherwise early exit.
                    if (DebugLogging)
                    {
                        Log.Write(GetType().Name, $"Dropping Non-reload from device {command.ControlPoint.ToString()} while being held by {command.ControlPoint.ToString()}");
                    }
                    return;
                }

                if (ClipSize > 0 && ammo <= 0)
                {
                    // Play 'empty' sound
                    if (OutOfAmmoSound != null)
                    {
                        ScenePrivate.PlaySoundAtPosition(OutOfAmmoSound, command.TargetingOrigin, ShotSettings);
                    }
                    if (DebugLogging)
                    {
                        Log.Write(GetType().Name, "Out of ammo");
                    }
                    return;
                }


                shotsFired++;
                ammo--;
                if (ShotSound != null)
                {
                    ScenePrivate.PlaySoundAtPosition(ShotSound, command.TargetingOrigin, ShotSettings);
                }


                var targetAgent = ScenePrivate.FindAgent(command.TargetingComponent.ObjectId);
                if (targetAgent != null)
                {
                    shotsHit++;
                    score += PointsPerPlayer;
                    if (PlayerHitSound != null)
                    {
                        ScenePrivate.PlaySoundAtPosition(PlayerHitSound, command.TargetingPosition, TargetSettings);
                    }
                    if (DebugLogging)
                    {
                        Log.Write(GetType().Name, "Player Hit");
                    }
                }
                else
                {
                    ObjectPrivate targetObject = ScenePrivate.FindObject(command.TargetingComponent.ObjectId);
                    if (targetObject != null)
                    {
                        Target target = targetObject.FindScripts <Target>("PewPewExample.Target").FirstOrDefault();
                        if (target != null)
                        {
                            if (DebugLogging)
                            {
                                Log.Write(GetType().Name, "Target hit");
                            }
                            score += target.Hit(holdingAgent, ScenePrivate);
                            shotsHit++;
                            return;
                        }
                    }
                    if (ShotMissSound != null)
                    {
                        ScenePrivate.PlaySoundAtPosition(ShotMissSound, command.TargetingOrigin, ShotSettings);
                    }
                    if (DebugLogging)
                    {
                        Log.Write(GetType().Name, "Miss:: " + command.ToString());
                    }
                }
            }
            catch (System.Exception) { } // ignore exceptions for not found agents.
        }
Beispiel #10
0
        private void fire(AnimationData obj)
        {
            ObjectPrivate avObject = ScenePrivate.FindObject(obj.ComponentId.ObjectId);

            StartCoroutine(fireRez, avObject.Position, avObject.ForwardVector, Sansar.Quaternion.FromLook(avObject.ForwardVector, Sansar.Vector.Up));
        }
Beispiel #11
0
        void OnTrigger(CommandData command)
        {
            try
            {
                if (CheckReload(command))
                {
                    return;
                }

                if (command.ControlPoint != heldHand)
                {
                    // Let them use the off hand to reload the gun, but otherwise early exit.
                    if (DebugLogging)
                    {
                        Log.Write(GetType().Name, $"Dropping Non-reload from device {command.ControlPoint.ToString()} while being held by {command.ControlPoint.ToString()}");
                    }
                    return;
                }

                if (ammo <= 0)
                {
                    // Play 'empty' sound
                    if (OutOfAmmoSound != null)
                    {
                        ScenePrivate.PlaySoundAtPosition(OutOfAmmoSound, command.TargetingOrigin, ShotSettings);
                    }
                    if (DebugLogging)
                    {
                        Log.Write(GetType().Name, "Out of ammo");
                    }
                    return;
                }


                shotsFired++;
                ammo--;

                var targetAgent = ScenePrivate.FindAgent(command.TargetingComponent.ObjectId);
                if (targetAgent != null)
                {
                    shotsHit++;
                    score += PointsPerPlayer;
                    if (PlayerHitSound != null)
                    {
                        ScenePrivate.PlaySoundAtPosition(PlayerHitSound, command.TargetingPosition, TargetSettings);
                    }
                    if (ShotHitSound != null)
                    {
                        ScenePrivate.PlaySoundAtPosition(ShotHitSound, command.TargetingOrigin, ShotSettings);
                    }
                    if (DebugLogging)
                    {
                        Log.Write(GetType().Name, "Player Hit");
                    }
                }
                else
                {
                    ObjectPrivate targetObject = ScenePrivate.FindObject(command.TargetingComponent.ObjectId);
                    if (targetObject != null)
                    {
                        Target target = targetObject.FindScripts <Target>("PewPewExample.Target").FirstOrDefault();
                        if (target != null)
                        {
                            if (ShotHitSound != null)
                            {
                                ScenePrivate.PlaySoundAtPosition(ShotHitSound, command.TargetingOrigin, ShotSettings);
                            }
                            if (DebugLogging)
                            {
                                Log.Write(GetType().Name, "Target hit");
                            }
                            score += target.Hit(holdingAgent, ScenePrivate);
                            shotsHit++;
                            return;
                        }
                    }
                    if (ShotMissSound != null)
                    {
                        ScenePrivate.PlaySoundAtPosition(ShotMissSound, command.TargetingOrigin, ShotSettings);
                    }
                    if (DebugLogging)
                    {
                        Log.Write(GetType().Name, "Miss:: " + command.ToString());
                    }
                }
            }
            catch (System.Exception) { } // ignore exceptions for not found agents.
        }
Beispiel #12
0
        protected override void SimpleInit()
        {
            // Any \n put in the parameter will not get converted to newlines, so convert them here.
            string prompt = MyInteraction.GetPrompt();

            if (prompt.Contains("\\n"))
            {
                MyInteraction.SetPrompt(prompt.Replace("\\n", "\n"));
            }

            if (!StartEnabled)
            {
                MyInteraction.SetEnabled(false);
            }

            if (!string.IsNullOrWhiteSpace(OnClick1))
            {
                EventNames.Add(OnClick1);
            }
            if (!string.IsNullOrWhiteSpace(OnClick2))
            {
                EventNames.Add(OnClick2);
            }
            if (!string.IsNullOrWhiteSpace(OnClick3))
            {
                EventNames.Add(OnClick3);
            }
            if (!string.IsNullOrWhiteSpace(OnClick4))
            {
                EventNames.Add(OnClick4);
            }


            SubscribeToAll(DisableEvent, (data) => { MyInteraction.SetEnabled(false); });
            SubscribeToAll(EnableEvent, (data) => { MyInteraction.SetEnabled(true); });
            SubscribeToAll(ResetEvent, (data) => { index = 0; });

            if (EventNames.Count > 0)
            {
                if (MaxEventsPerSecond >= 100 || MaxEventsPerSecond <= 0)
                {
                    MyInteraction.Subscribe((InteractionData data) =>
                    {
                        if (DisableOnClick)
                        {
                            MyInteraction.SetEnabled(data.AgentId, false);
                        }

                        SimpleData sd     = new SimpleData(this);
                        sd.SourceObjectId = ObjectPrivate.ObjectId;
                        sd.AgentInfo      = ScenePrivate.FindAgent(data.AgentId)?.AgentInfo;
                        sd.ObjectId       = sd.AgentInfo != null ? sd.AgentInfo.ObjectId : ObjectId.Invalid;
                        SendToAll(EventNames[index], sd);
                        index = (index + 1) % EventNames.Count;
                    });
                }
                else
                {
                    TimeSpan waitTime = TimeSpan.FromSeconds(1.0 / MaxEventsPerSecond);
                    while (true)
                    {
                        InteractionData data = (InteractionData)WaitFor(MyInteraction.Subscribe);
                        if (DisableOnClick)
                        {
                            MyInteraction.SetEnabled(data.AgentId, false);
                        }

                        SimpleData sd = new SimpleData(this);
                        sd.SourceObjectId = ObjectPrivate.ObjectId;
                        sd.AgentInfo      = ScenePrivate.FindAgent(data.AgentId)?.AgentInfo;
                        sd.ObjectId       = sd.AgentInfo != null ? sd.AgentInfo.ObjectId : ObjectId.Invalid;
                        SendToAll(EventNames[index], sd);
                        index = (index + 1) % EventNames.Count;
                        Wait(waitTime);
                    }
                }
            }
        }
Beispiel #13
0
 void OnAddUser(UserData data)
 {
     OnAddUser(ScenePrivate.FindAgent(data.User));
 }
Beispiel #14
0
        void OnSelect(CommandData command)
        {
            try
            {
                if (!FreeCamEnabled && command.CameraControlMode == CameraControlMode.FlyCam)
                {
                    AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                    user.SendChat("This device does not work in Free Cam mode, return to 1st or 3rd person views to use this device.");
                    return;
                }

                switch (command.ControlPoint)
                {
                case ControlPointType.DesktopGrab:
                    if (!MouseLookEnabled && command.MouseLookMode)
                    {
                        AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                        user.SendChat("This device does not work in desktop Mouse Look Mode: press Escape to enter or exit Mouse Look.");
                        return;
                    }
                    if (!FreeClickEnabled && !command.MouseLookMode)
                    {
                        AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                        user.SendChat("This device does not work in desktop Free Click Mode: press Escape to enter or exit Mouse Look.");
                        return;
                    }
                    break;

                case ControlPointType.LeftTool:
                case ControlPointType.RightTool:
                    if (!VREnabled)
                    {
                        AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                        user.SendChat("This device does not work in VR.");
                        return;
                    }

                    // Check hand after CheckReload which handles "shooting yourself to reload"
                    // If they grabbed it in desktop let them use it from whichever hand now? I guess?
                    if (heldHand != ControlPointType.DesktopGrab && command.ControlPoint != heldHand)
                    {
                        return;
                    }
                    break;

                default:
                    break;
                }

                SendToAll(EveryCommandEvent, simpleData);

                var targetAgent = ScenePrivate.FindAgent(command.TargetingComponent.ObjectId);
                if (targetAgent != null)
                {
                    SimpleData targetSimpleData = new SimpleData(this);
                    targetSimpleData.AgentInfo      = targetAgent.AgentInfo;
                    targetSimpleData.ObjectId       = targetSimpleData.AgentInfo.ObjectId;
                    targetSimpleData.SourceObjectId = simpleData.SourceObjectId;

                    SendToAll(PlayerSelectedEvent, targetSimpleData);
                }
                else
                {
                    ObjectPrivate targetObject = ScenePrivate.FindObject(command.TargetingComponent.ObjectId);
                    if (targetObject != null)
                    {
                        SimpleData targetSimpleData = new SimpleData(this);
                        targetSimpleData.AgentInfo      = null;
                        targetSimpleData.ObjectId       = targetObject.ObjectId;
                        targetSimpleData.SourceObjectId = simpleData.SourceObjectId;

                        ITarget target = targetObject.FindScripts <ITarget>("Simple.Target").FirstOrDefault();
                        if (target == null ||
                            (SameGroupRequired && target.GetGroupTag() != base.Group))
                        {
                            SendToAll(ObjectSelectedEvent, targetSimpleData);
                            return;
                        }
                        else
                        {
                            target.Hit(holdingAgent, command);
                            SendToAll(TargetSelectedEvent, targetSimpleData);
                            return;
                        }
                    }

                    SendToAll(NothingSelectedEvent, simpleData);
                }
            }
            catch (System.Exception) { } // ignore exceptions for not found agents.
        }
Beispiel #15
0
        void OnTrigger(CommandData command)
        {
            try
            {
                if (!FreeCamEnabled && command.CameraControlMode == CameraControlMode.FlyCam)
                {
                    AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                    user.SendChat("This device does not work in Free Cam mode, return to 1st or 3rd person views to use this device.");
                    return;
                }

                switch (command.ControlPoint)
                {
                case ControlPointType.DesktopGrab:
                    if (!MouseLookEnabled && command.MouseLookMode)
                    {
                        AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                        user.SendChat("This device does not work in desktop Mouse Look Mode: press Escape to enter or exit Mouse Look.");
                        return;
                    }
                    if (!FreeClickEnabled && !command.MouseLookMode)
                    {
                        AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                        user.SendChat("This device does not work in desktop Free Click Mode: press Escape to enter or exit Mouse Look.");
                        return;
                    }
                    break;

                case ControlPointType.LeftTool:
                case ControlPointType.RightTool:
                    if (!VREnabled)
                    {
                        AgentPrivate user = ScenePrivate.FindAgent(holdingAgent.SessionId);
                        user.SendChat("This device does not work in VR.");
                        return;
                    }

                    // If they grabbed it in desktop let them use it from whichever hand now? I guess?
                    if (heldHand != ControlPointType.DesktopGrab && command.ControlPoint != heldHand)
                    {
                        return;
                    }
                    break;

                default:
                    break;
                }

                if (ClipSize > 0 && ammo <= 0)
                {
                    SendToAll(OutOfAmmoEvent, simpleData);
                    return;
                }

                SendToAll(ShotFiredEvent, simpleData);
                shotsFired++;
                ammo--;

                var targetAgent = ScenePrivate.FindAgent(command.TargetingComponent.ObjectId);
                if (targetAgent != null)
                {
                    shotsHit++;
                    score += PointsPerPlayer;
                    SendToAll(PlayerHitEvent, simpleData);

                    SimpleData targetSimpleData = new SimpleData(this);
                    targetSimpleData.AgentInfo      = targetAgent.AgentInfo;
                    targetSimpleData.ObjectId       = targetSimpleData.AgentInfo.ObjectId;
                    targetSimpleData.SourceObjectId = simpleData.SourceObjectId;

                    SendToAll(ShotHitEvent, targetSimpleData);
                }
                else
                {
                    ObjectPrivate targetObject = ScenePrivate.FindObject(command.TargetingComponent.ObjectId);
                    if (targetObject != null)
                    {
                        ITarget target = targetObject.FindScripts <ITarget>("Simple.Target").FirstOrDefault();
                        if (target != null &&
                            (!SameGroupRequired || target.GetGroupTag() == Group))
                        {
                            SimpleData targetSimpleData = new SimpleData(this);
                            targetSimpleData.AgentInfo      = null;
                            targetSimpleData.ObjectId       = targetObject.ObjectId;
                            targetSimpleData.SourceObjectId = simpleData.SourceObjectId;

                            SendToAll(ShotHitEvent, targetSimpleData);
                            score += target.Hit(holdingAgent, command);
                            shotsHit++;
                            return;
                        }
                    }

                    SendToAll(ShotMissEvent, simpleData);
                }
            }
            catch (System.Exception) { } // ignore exceptions for not found agents.
        }
Beispiel #16
0
    private void ParseCommands(string DataCmdIn)
    {
        Errormsg = "No Errors";
        Log.Write("DataCmdIn: " + DataCmdIn);
        if (DataCmdIn.Contains("/"))
        {
            strErrors = false;
            if (DataCmdIn.Contains("/forcevideo"))
            {
                //play video
                IsWatchFormat = false;
                Log.Write("video: " + video);
                Log.Write("video length: " + video.Length);
                video = DataCmdIn.Substring(12, DataCmdIn.Length - 12);
                PlayVideo(video);
            }
            if (DataCmdIn.Contains("/forcecurrentvideo"))
            {
                //play video
                IsWatchFormat = false;
                //Log.Write("videoIn: " + videoIn);
                //Log.Write("videoIn length: " + videoIn.Length);
                //video = DataCmdIn.Substring(12, DataCmdIn.Length - 12);
                video = videoIn.Trim();
                //Log.Write("video length: " + video.Length);
                PlayVideo(video);
            }
            if (DataCmdIn.Contains("/next"))
            {
                string VideoToPlay = null;
                //Log.Write("PlayList Size: " + PlayList.Count());
                //Log.Write("playListPosition: " + playListPosition);
                if (PlayList.Count() == 0)
                {
                    Log.Write("No Playlist");
                }
                else
                if (playListPosition > PlayList.Count() - 1)
                {
                    playListPosition = 1;
                }
                else
                {
                    playListPosition++;
                }
                VideoToPlay = PlayList[playListPosition - 1];
                //Log.Write("video: " + VideoToPlay);
                videoIn = VideoToPlay;
                if (VideoToPlay.Contains("/watch?v="))
                {
                    IsWatchFormat = true;
                    VideoToPlay   = URLToEmbedFormat(VideoToPlay);
                }
                PlayVideo(VideoToPlay);
            }
            if (DataCmdIn.Contains("/previous"))
            {
                string VideoToPlay = null;
                Log.Write("PlayList Size: " + PlayList.Count());
                Log.Write("playListPosition: " + playListPosition);
                if (PlayList.Count() == 0)
                {
                    Log.Write("No Playlist");
                }
                else if (playListPosition < 1)
                {
                    playListPosition = PlayList.Count() - 1;
                }
                else
                {
                    playListPosition--;
                }
                VideoToPlay = PlayList[playListPosition];
                Log.Write("video: " + VideoToPlay);
                videoIn = VideoToPlay;
                if (VideoToPlay.Contains("/watch?v="))
                {
                    IsWatchFormat = true;
                    VideoToPlay   = URLToEmbedFormat(VideoToPlay);
                }
                PlayVideo(VideoToPlay);
            }
            if (DataCmdIn.Contains("/playlist"))
            {
                ScenePrivate.Chat.MessageAllUsers("Playlist Not Yet Implemented");

                /*
                 * playListPosition = 0;
                 * string VideoToPlay = null;
                 * keepPlaying = true;
                 * do
                 * {
                 *  VideoToPlay = PlayList[playListPosition];
                 *  Log.Write("video: " + VideoToPlay);
                 *  videoIn = VideoToPlay;
                 *  if (VideoToPlay.Contains("/watch?v="))
                 *  {
                 *      IsWatchFormat = true;
                 *      VideoToPlay = URLToEmbedFormat(VideoToPlay);
                 *  }
                 *  PlayVideo(VideoToPlay);
                 *  Log.Write("playListPosition" + playListPosition);
                 *  if (playListPosition >= PlayList.Count())
                 *  {
                 *      playListPosition = 0;
                 *  }
                 *  else
                 *  {
                 *      playListPosition++;
                 *  }
                 * } while (keepPlaying);
                 */
            }
            if (DataCmdIn.Contains("/shuffle"))
            {
                ScenePrivate.Chat.MessageAllUsers("Shuffle Not Yet Implemented");
            }

            if ((DataCmdIn.Contains("/video")) || (DataCmdIn.Contains("/stream")))
            {
                //play video
                IsWatchFormat = false;
                video         = DataCmdIn.Substring(7, DataCmdIn.Length - 7);
                videoIn       = video;
                Log.Write("video: " + video);
                if (DataCmdIn.Contains("/watch?v="))
                {
                    IsWatchFormat = true;
                    video         = URLToEmbedFormat(DataCmdIn);
                    Log.Write("New Video: " + video);
                }
                if (DataCmdIn.Contains("Youtu.be"))
                {
                    IsWatchFormat = true;
                    video         = ShortenedURLToEmbedFormat(DataCmdIn);
                    Log.Write("New Video: " + video);
                }
                PlayVideo(video);
            }
            if (DataCmdIn.Contains("/play"))
            {
                //play video
                string VideoToPlay = null;
                Log.Write("DataCmdIn: " + DataCmdIn.Trim());
                switch (DataCmdIn.Trim())
                {
                case "/play1":
                    if (Play1.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play1;
                        playListPosition = 1;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play1");
                    }
                    break;

                case "/play2":
                    if (Play2.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play2;
                        playListPosition = 2;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play2");
                    }
                    break;

                case "/play3":
                    if (Play3.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play3;
                        playListPosition = 3;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play3");
                    }
                    break;

                case "/play4":
                    if (Play4.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play4;
                        playListPosition = 4;
                    }
                    else
                    {
                        Log.Write("No Play4");
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play4");
                    }
                    break;

                case "/play5":
                    if (Play5.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play5;
                        playListPosition = 5;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play5");
                    }
                    break;

                case "/play6":
                    if (Play6.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play6;
                        playListPosition = 6;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play6");
                    }
                    break;

                case "/play7":
                    if (Play7.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play7;
                        playListPosition = 7;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play7");
                    }
                    break;

                case "/play8":
                    if (Play8.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play8;
                        playListPosition = 8;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play8");
                    }
                    break;

                case "/play9":
                    if (Play9.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play9;
                        playListPosition = 9;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play9");
                    }
                    break;

                case "/play10":
                    if (Play10.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play10;
                        playListPosition = 10;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play10");
                    }
                    break;

                case "/play11":
                    if (Play11.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play11;
                        playListPosition = 11;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play11");
                    }
                    break;

                case "/play12":
                    if (Play12.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play12;
                        playListPosition = 12;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play12");
                    }
                    break;

                case "/play13":
                    if (Play13.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play13;
                        playListPosition = 13;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play13");
                    }
                    break;

                case "/play14":
                    if (Play14.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play14;
                        playListPosition = 14;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play14");
                    }
                    break;

                case "/play15":
                    if (Play15.Length > 0)
                    {
                        IsWatchFormat    = false;
                        VideoToPlay      = Play15;
                        playListPosition = 15;
                    }
                    else
                    {
                        ScenePrivate.Chat.MessageAllUsers("No Video in Slot Play15");
                    }
                    break;

                default:
                    Errormsg = "Must be Play1 thru Play15";
                    break;
                }

                Log.Write("PlayListPosition: " + playListPosition);
                Log.Write("video: " + VideoToPlay);
                videoIn = VideoToPlay;
                if (VideoToPlay.Contains("/watch?v="))
                {
                    IsWatchFormat = true;
                    VideoToPlay   = URLToEmbedFormat(VideoToPlay);
                }
                PlayVideo(VideoToPlay);
            }
            if (DataCmdIn.Contains("/pause") && IsWatchFormat)
            {
                intVideoCurrentTime = (int)(DateTime.Now - VideoStartTime).TotalSeconds;
                video = "https://www.youtube.com/embed/" + EmbedVideoID + "?rel=0&end=1&controls=0&showinfo=0&autoplay=1&allowfullscreen";
                Log.Write("Video on pause: " + video);
                ScenePrivate.OverrideMediaSource(video, ScreenWidth, ScreenHeight);
            }
            if (DataCmdIn.Contains("/resume") && IsWatchFormat)
            {
                intVideoCurrentTime = (int)(DateTime.Now - VideoStartTime).TotalSeconds;
                video = "https://www.youtube.com/embed/" + EmbedVideoID + "?rel=0&start=" + intVideoCurrentTime.ToString() + "&controls=0&showinfo=0&autoplay=1&allowfullscreen";
                Log.Write("Video on resume: " + video);
                ScenePrivate.OverrideMediaSource(video, ScreenWidth, ScreenHeight);
            }
            if (DataCmdIn.Contains("/stop") && IsWatchFormat)
            {
                intVideoCurrentTime = 0;
                VideoStartTime      = DateTime.Now;
                EmbedVideoID        = "4wTPTh6-sSo";
                video = "https://www.youtube.com/embed/" + EmbedVideoID + "  ?rel=0&controls=0&showinfo=0&autoplay=1&allowfullscreen";
                Log.Write("Video on pause: " + video);
                ScenePrivate.OverrideMediaSource(video, ScreenWidth, ScreenHeight);
                keepPlaying = false;
            }
            if (DataCmdIn.Contains("/volumeUp"))
            {
                Log.Write("In volumeUp");
                float curLoudness = currentPlayHandle.GetLoudness();
                curLoudness = curLoudness + 5;
                currentPlayHandle.SetLoudness(curLoudness);
            }
            if (DataCmdIn.Contains("/volumeDown"))
            {
                Log.Write("In volumeDown");
                float curLoudness = currentPlayHandle.GetLoudness();
                curLoudness = curLoudness - 5;
                currentPlayHandle.SetLoudness(curLoudness);
            }

            /*
             *
             * if (DataCmdIn.Contains("/commands"))
             * {
             *  DisplayHelp(agent);
             *
             * }
             */
        }
    }
Beispiel #17
0
 void OnRemoveUser(UserData data)
 {
     VisibleToSessions.Remove(data.User);
     OnRemoveUser(ScenePrivate.FindAgent(data.User));
 }
Beispiel #18
0
    void OnChat(ChatData data)
    {
        AgentPrivate agent = ScenePrivate.FindAgent(data.SourceId);

        if (!IsAccessAllowed(agent))
        {
            return;
        }

        string[] chatWords = data.Message.Split(' ');

        if (chatWords.Length < 1)
        {
            return;
        }

        string command = chatWords[0];

        if (!_commandsUsage.ContainsKey(command))
        {
            return;
        }

        if (command == "/help" || chatWords.Length < 2)
        {
            string helpMessage = "MediaChatCommand usage:";
            foreach (var kvp in _commandsUsage)
            {
                helpMessage += "\n" + kvp.Key + " " + kvp.Value;
            }

            try
            {
                agent.SendChat(helpMessage);
            }
            catch
            {
                // Agent left
            }

            return;
        }

        string medialUrl = "";

        if (command == "/media" || chatWords[1].StartsWith("http"))
        {
            medialUrl = chatWords[1];
        }
        else if (command == "/yt" || command == "/youtube")
        {
            string videoId = chatWords[1];
            medialUrl = string.Format("https://www.youtube.com/embed/{0}?autoplay=1&loop=1&playlist={0}&controls=0", videoId);

            if (chatWords.Length > 2)
            {
                int startTime = 0;
                if (int.TryParse(chatWords[2], out startTime))
                {
                    medialUrl += "&start=" + startTime;
                }
            }
        }
        else if (command == "/ytlive")
        {
            string livestreamId = chatWords[1];
            medialUrl = string.Format("https://www.youtube.com/embed/live_stream?channel={0}&autoplay=1", livestreamId);
        }
        else if (command == "/ytpl")
        {
            string playlistId = chatWords[1];
            medialUrl = string.Format("https://www.youtube.com/embed?%20listType=playlist%20&list={0}&loop=1&autoplay=1&controls=0", playlistId);
        }
        else if (command == "/twitch")
        {
            string channelName = chatWords[1];
            medialUrl = string.Format("http://player.twitch.tv/?channel={0}&quality=source&volume=1", channelName);
        }
        else if (command == "/twitchv")
        {
            string videoId = chatWords[1];
            medialUrl = string.Format("http://player.twitch.tv/?video={0}&quality=source&volume=1", videoId);
        }
        else if (command == "/vimeo")
        {
            string videoId = chatWords[1];
            medialUrl = string.Format("https://player.vimeo.com/video/{0}?autoplay=1&loop=1&autopause=0", videoId);
        }

        bool throttled = false;

        try
        {
            ScenePrivate.OverrideMediaSource(medialUrl);

            agent.SendChat("Media URL successfully updated to " + medialUrl);
            Log.Write("New media URL: " + medialUrl);
        }
        catch (ThrottleException)
        {
            throttled = true;
            Log.Write("Throttled: Unable to update media URL.");
        }
        catch
        {
            // Agent left
        }

        if (throttled)
        {
            try
            {
                agent.SendChat("Media URL update was throttled.  Try again.");
            }
            catch
            {
                // Agent left
            }
        }
    }
Beispiel #19
0
        void OnAddUser(UserData data)
        {
            AgentPrivate agent = ScenePrivate.FindAgent(data.User);

            OnAddAgent(agent);
        }
    void OnChat(ChatData data)
    {
        AgentPrivate agent = ScenePrivate.FindAgent(data.SourceId);

        if (!IsAccessAllowed(agent))
        {
            return;
        }

        string[] chatWords = data.Message.Split(' ');

        if (chatWords.Length < 1)
        {
            return;
        }

        string command = chatWords[0];

        if (!_commandsUsage.ContainsKey(command))
        {
            return;
        }

        if (command == "/help")
        {
            string helpMessage = "AudioStreamChatCommand usage:";
            foreach (var kvp in _commandsUsage)
            {
                helpMessage += "\n" + kvp.Key + " " + kvp.Value;
            }
            agent.SendChat(helpMessage);
            return;
        }

        // if (command == "/stream")
        string medialUrl = (chatWords.Length < 2 ? "" : chatWords[1]);

        bool throttled = false;

        try
        {
            ScenePrivate.OverrideAudioStream(medialUrl);

            agent.SendChat("Audio Stream URL successfully updated to " + medialUrl);
            Log.Write("New audio stream URL: " + medialUrl);
        }
        catch (ThrottleException)
        {
            throttled = true;
            Log.Write("Throttled: Unable to update audio stream URL.");
        }
        catch
        {
            // Agent left
        }

        if (throttled)
        {
            try
            {
                agent.SendChat("Audio stream URL update was throttled.  Try again.");
            }
            catch
            {
                // Agent left
            }
        }
    }
Beispiel #21
0
        private void OnCollision(CollisionData data)
        {
            SimpleData sd = new SimpleData(this);

            sd.ObjectId       = data.HitComponentId.ObjectId;
            sd.AgentInfo      = ScenePrivate.FindAgent(sd.ObjectId)?.AgentInfo;
            sd.SourceObjectId = ObjectPrivate.ObjectId;

            bool isAgentPunch = (data.HitControlPoint != ControlPointType.Invalid);

            if (!enabled)
            {
                // No events are sent while disabled, just manage agentsInTrigger
                if (data.Phase == CollisionEventPhase.TriggerExit)
                {
                    if (agentsInTrigger.ContainsKey(sd.ObjectId) && !isAgentPunch)
                    {
                        agentsInTrigger.Remove(sd.ObjectId);
                    }
                }
                else if (data.Phase == CollisionEventPhase.TriggerEnter)
                {
                    if (sd.AgentInfo != null && !isAgentPunch && !agentsInTrigger.ContainsKey(sd.ObjectId))
                    {
                        agentsInTrigger[sd.ObjectId] = sd.AgentInfo;
                    }
                }
                return;
            }

            if (data.Phase == CollisionEventPhase.TriggerExit)
            {
                if (sd.ObjectId == ObjectId.Invalid)
                {
                    if (userLoggedOut > 0)
                    {
                        // This object has left the scene and it was a user whose events were managed in the user subscription.
                        --userLoggedOut;
                    }
                    else
                    {
                        // Object that was destroyed while inside the collision volume
                        SendToAll(OnObjectExit, sd);
                    }
                    return;
                }

                // We determine agent or not on exit by whether they are in the agentsInTrigger Dictionary
                // This helps handle the case where a user logs out from within the trigger volume - after which their AgentInfo will be null.
                AgentInfo storedInfo;
                if (agentsInTrigger.TryGetValue(sd.ObjectId, out storedInfo))
                {
                    // Use the stored info, in case the user has logged out.
                    sd.AgentInfo = storedInfo;
                    if (isAgentPunch)
                    {
                        SendToAll(OnAgentPunchExit, sd);
                    }
                    else
                    {
                        SendToAll(OnAgentExit, sd);
                        agentsInTrigger.Remove(sd.ObjectId);

                        if (agentsInTrigger.Count == 0)
                        {
                            SendToAll(OnLastAgentTriggerExit, sd);
                        }
                    }
                }
                else
                {
                    SendToAll(OnObjectExit, sd);
                }
            }
            else if (data.Phase == CollisionEventPhase.TriggerEnter || data.Phase == CollisionEventPhase.Invalid)
            {
                if (sd.AgentInfo != null)
                {
                    if (isAgentPunch)
                    {
                        SendToAll(OnAgentPunchEnter, sd);
                    }
                    else
                    {
                        SendToAll(OnAgentEnter, sd);

                        // Only track agents in the object if it is an enter event.
                        if (data.Phase == CollisionEventPhase.TriggerEnter)
                        {
                            if (agentsInTrigger.Count == 0)
                            {
                                SendToAll(OnFirstAgentTriggerEnter, sd);
                            }

                            agentsInTrigger[sd.ObjectId] = sd.AgentInfo;
                        }
                    }
                }
                else
                {
                    SendToAll(OnObjectEnter, sd);
                }
            }
        }
 void ChatLog(SessionId sessionId, string log)
 {
     Log.Write(log);
     ScenePrivate.FindAgent(sessionId)?.SendChat(log);
 }
    public override void Init()
    {
        // no init needed. The following is an example of using the IBank:
        IBank bank = ScenePrivate.FindReflective <IBank>("CoroutineLockExample").FirstOrDefault();

        if (bank != null)
        {
            bank.CreateAccount("bob", 100);
            bank.CreateAccount("sue", 100);
            bank.CreateAccount("joe", 100);

            StartCoroutine(() =>
            {   // Send some money from joe to sue every 0.3 seconds
                while (true)
                {
                    bank.TransferMoney("joe", "sue", 3);
                    Wait(TimeSpan.FromSeconds(0.3));
                }
            });

            StartCoroutine(() =>
            {   // Send some money from sue to bob every 0.1 seconds
                while (true)
                {
                    bank.TransferMoney("sue", "bob", 1);
                    Wait(TimeSpan.FromSeconds(0.1));
                }
            });

            StartCoroutine(() =>
            {   // Send some money from sue to bob every 0.1 seconds
                while (true)
                {
                    bank.TransferMoney("bob", "joe", 2);
                    Wait(TimeSpan.FromSeconds(0.2));
                }
            });

            StartCoroutine(() =>
            {   // Send some money all around
                while (true)
                {
                    bank.TransferMoney("joe", "bob", 10);
                    bank.TransferMoney("joe", "sue", 10);
                    bank.TransferMoney("sue", "bob", 10);
                    bank.TransferMoney("sue", "joe", 10);
                    bank.TransferMoney("bob", "sue", 10);
                    bank.TransferMoney("bob", "joe", 10);
                    Wait(TimeSpan.FromSeconds(0.1));
                }
            });

            // "weekly" reports:
            StartCoroutine(() =>
            {
                while (true)
                {
                    Wait(TimeSpan.FromSeconds(300));
                    // Note that it is possible for transactions to get in between the reporting in here, due to threading.
                    // We aren't actually getting the entire report atomically here.
                    Log.Write($"Balances: Bob={bank.GetBalance("bob")} Sue={bank.GetBalance("sue")} Joe={bank.GetBalance("joe")}");
                }
            });

            // "weekly" atomic reports:
            StartCoroutine(() =>
            {
                while (true)
                {
                    Wait(TimeSpan.FromSeconds(300));
                    // This report is generated inside the lock and so should be atomic: balances should always total 300 in this example.
                    Log.Write(bank.GetReport());
                }
            });
        }
    }
        void OnAddUser(UserData data)
        {
            AgentPrivate agent = ScenePrivate.FindAgent(data.User);

            if (agent == null || !agent.IsValid)
            {
                return;
            }

            Sansar.Simulation.Quest quest = null;
            AgentInfo agentInfo           = null;

            try
            {
                agentInfo = agent.AgentInfo;

                var questData = WaitFor(QuestDefinition.GetQuest, agentInfo.SessionId) as QuestDefinition.GetQuestData;
                if (questData.Success)
                {
                    quest = questData.Quest;
                }
            }
            catch
            {
                Log.Write(LogLevel.Error, "Failed to get agent info, user may have left experience.");
                return;
            }

            if (quest != null)
            {
                OnAgentJoinExperience(agentInfo, quest);

                switch (quest.GetState())
                {
                case QuestState.None:
                    OnAgentQuestAvailable(agentInfo, quest);
                    break;

                case QuestState.Offered:
                    OnAgentOfferedQuest(agentInfo, quest);
                    break;

                case QuestState.Active:
                    OnAgentStartedQuest(agentInfo, quest);
                    break;

                case QuestState.Completed:
                    OnAgentCompletedQuest(agentInfo, quest);
                    break;
                }

                quest.Subscribe(QuestState.Offered, (QuestData d) =>
                {
                    OnAgentOfferedQuest(agentInfo, quest);
                });

                quest.Subscribe(QuestState.Active, (QuestData d) =>
                {
                    OnAgentStartedQuest(agentInfo, quest);
                });

                quest.Subscribe(QuestState.Completed, (QuestData d) =>
                {
                    OnAgentCompletedQuest(agentInfo, quest);
                });

                foreach (var objective in quest.Objectives)
                {
                    objective.Subscribe(ObjectiveState.Active, (ObjectiveData d) => ChatLogQuest(agentInfo.SessionId, quest));
                    objective.Subscribe(ObjectiveState.Locked, (ObjectiveData d) => ChatLogQuest(agentInfo.SessionId, quest));
                    objective.Subscribe(ObjectiveState.Completed, (ObjectiveData d) => ChatLogQuest(agentInfo.SessionId, quest));
                }

                if (OfferOnSceneEnter && (quest.GetState() == QuestState.None || quest.GetState() == QuestState.Offered))
                {
                    OfferToAgent(agentInfo.SessionId);
                }
            }
        }
Beispiel #25
0
        void Setup(StreamChannel channel, string eventName, float loudness)
        {
            unsubscribes += SubscribeToAll(eventName, (ScriptEventData subData) =>
            {
                StopSound(true);

                if (PrivateMedia)
                {
                    ISimpleData simpleData = subData.Data?.AsInterface <ISimpleData>();

                    if (simpleData != null && simpleData.AgentInfo != null)
                    {
                        AgentPrivate agent = ScenePrivate.FindAgent(simpleData.AgentInfo.SessionId);

                        if (agent != null && agent.IsValid)
                        {
                            try
                            {
                                if (Spatialized)
                                {
                                    if (audio != null)
                                    {
                                        currentPlayHandle = agent.PlayStreamOnComponent(channel, audio, loudness);
                                    }
                                    else
                                    {
                                        currentPlayHandle = agent.PlayStreamAtPosition(channel, ObjectPrivate.Position, loudness);
                                    }
                                }
                                else
                                {
                                    currentPlayHandle = agent.PlayStream(channel, loudness);
                                }
                            }
                            catch (ThrottleException)
                            {
                                // Throttled
                                Log.Write(LogLevel.Warning, "PlayStream request throttle hit. Stream not set.");
                            }
                            catch (NullReferenceException)
                            {
                                // User Left, ignore.
                            }
                        }
                    }
                }
                else
                {
                    try
                    {
                        if (Spatialized)
                        {
                            if (audio != null)
                            {
                                currentPlayHandle = audio.PlayStreamOnComponent(channel, loudness);
                            }
                            else
                            {
                                currentPlayHandle = ScenePrivate.PlayStreamAtPosition(channel, ObjectPrivate.Position, loudness);
                            }
                        }
                        else
                        {
                            currentPlayHandle = ScenePrivate.PlayStream(channel, loudness);
                        }
                    }
                    catch (ThrottleException)
                    {
                        // Throttled
                        Log.Write(LogLevel.Warning, "PlayStream request throttle hit. Stream not set.");
                    }
                }
            });
        }
    public void RezCannonball(Sansar.Vector initial_pos, Sansar.Quaternion rotation, Sansar.Vector vel)
    {
        ScenePrivate.CreateClusterData createData = null;
        try
        {
            try
            {
                if (Projectile != null)
                {
                    createData = (ScenePrivate.CreateClusterData)WaitFor(ScenePrivate.CreateCluster, Projectile,
                                                                         initial_pos,
                                                                         rotation,
                                                                         vel);
                }
                else
                {   // No projectile override - just use cannon balls.
                    createData = (ScenePrivate.CreateClusterData)WaitFor(ScenePrivate.CreateCluster, "Export/CannonBall/",
                                                                         initial_pos,
                                                                         rotation,
                                                                         vel);
                }
            }
            catch (ThrottleException e)
            {
                Log.Write($"Too many rezzes! Throttle rate is {e.MaxEvents} per {e.Interval.TotalSeconds}.");
                RezThrottled = true;
                Wait(e.Interval - e.Elapsed); // Wait out the rest of the interval before trying again.
                RezThrottled = false;
                return;
            }

            if (createData.Success)
            {
                ObjectPrivate obj = createData.ClusterReference.GetObjectPrivate(0);
                if (obj != null)
                {
                    RigidBodyComponent RigidBody = null;
                    if (obj.TryGetFirstComponent(out RigidBody))
                    {
                        //exit after 3 hits or 1 character hit
                        for (int i = 0; i < 3; i++)
                        {
                            CollisionData data = (CollisionData)WaitFor(RigidBody.Subscribe, CollisionEventType.AllCollisions, ComponentId.Invalid);

                            if ((data.EventType & CollisionEventType.CharacterContact) != 0)
                            {
                                // Use the scene to find the full object API of the other object.
                                AgentPrivate hit = ScenePrivate.FindAgent(data.HitComponentId.ObjectId);
                                if (hit != null)
                                {
                                    ObjectPrivate otherObject = ScenePrivate.FindObject(data.HitComponentId.ObjectId);
                                    if (otherObject != null)
                                    {
                                        if (Hit_Sound != null)
                                        {
                                            ScenePrivate.PlaySoundAtPosition(Hit_Sound, otherObject.Position, SoundSettings);
                                        }

                                        if (Teleport_On_Hit)
                                        {
                                            AnimationComponent anim;
                                            if (otherObject.TryGetFirstComponent(out anim))
                                            {
                                                anim.SetPosition(SpawnPoints[rng.Next(SpawnPoints.Count)]);
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Log.Write(e.ToString());
        }
        finally
        {
            if (createData.ClusterReference != null)
            {
                try
                {
                    createData.ClusterReference.Destroy();
                }
                catch (Exception) { }
            }
        }
    }
Beispiel #27
0
    private void onChat(ChatData data)
    {
        AgentPrivate agent = ScenePrivate.FindAgent(data.SourceId);

        if (IsAdmin(agent))
        {
            string[] chatWords = data.Message.Split(' ');

            if (chatWords.Length < 1)
            {
                if (DebugLogging)
                {
                    Log.Write("Chat message not long enough.");
                }
                return;
            }

            string command = chatWords[0];

            if (!_commandsUsage.ContainsKey(command))
            {
                if (DebugLogging)
                {
                    Log.Write("Command not found in dictionary." + command);
                }
                return;
            }

            if (DebugLogging)
            {
                Log.Write("Command = " + command);
            }

            switch (command)
            {
            case "/help":
                onShowHelp(agent);
                break;

            case "/log":
                onShowLog(agent);
                break;

            case "/reset":
                onReset();
                break;

            case "/door":
                onDoorCommand(chatWords[1]);
                break;

            case "/ban":
                onBanCommand(chatWords[1]);
                break;

            case "/unban":
                onUnBanCommand(chatWords[1]);
                break;

            case "/admin":
                onAddAdmin(chatWords[1]);
                break;

            case "/radmin":
                onRemoveAdmin(chatWords[1]);
                break;

            case "/vote":
                onVote(chatWords[1]);
                break;

            default: break;
            }
        }
    }
    private void UpdateLoop()
    {
        float Tick      = 0.01f;
        float AngleStep = 5 * OpenAngle * Tick / SecondsToOpen;

        TimeSpan Moment = TimeSpan.FromSeconds(Tick);

        float Angle = 0.0f;

        while (true)
        {
            Wait(Moment);

            // If we're in the process of opening or closing, we'll adjust the angle a little toward the target
            if (Opening)
            {
                if (OpenOut)
                {
                    Angle -= AngleStep;
                    if (Angle < -OpenAngle)
                    {
                        Angle = -OpenAngle;
                    }
                }
                else
                {
                    Angle += AngleStep;
                    if (Angle > OpenAngle)
                    {
                        Angle = OpenAngle;
                    }
                }

                // If it's been a while since we've heard an open signal, let's start closing the door
                if (DateTime.Now.Subtract(LatestOpenSignal).TotalSeconds >= SecondsBeforeClose)
                {
                    Opening = false;
                    if (CloseSound != null)
                    {
                        ScenePrivate.PlaySound(CloseSound, PlaySettings.PlayOnce);
                    }
                }
            }
            else
            {
                if (OpenOut)
                {
                    Angle += AngleStep;
                    if (Angle > 0f)
                    {
                        Angle = 0f;
                    }
                }
                else
                {
                    Angle -= AngleStep;
                    if (Angle < 0f)
                    {
                        Angle = 0f;
                    }
                }
            }

            // Compute the new position and rotation of the door
            Quaternion Rotation = Quaternion.FromEulerAngles(new Vector(0, 0, Angle, 0));
            Quaternion NewOri   = ClosedOrientation * Rotation;
            Vector     NewPos   = ClosedPosition - HingeOffset.Rotate(ref Rotation);

            // Update the door's position and orientation
            DoorBody.SetAngularVelocity(Vector.Zero);
            DoorBody.SetLinearVelocity(Vector.Zero);
            DoorBody.SetPosition(NewPos);
            DoorBody.SetOrientation(QuaternionToVector(NewOri));
        }
    }
Beispiel #29
0
    private void ExecuteMovement(ScriptEventData data)
    {
        Log.Write("In Execute Animation data message: " + data.Message);
        ISimpleData  ExecuteData  = data.Data?.AsInterface <ISimpleData>();
        AgentPrivate ExecuteAgent = ScenePrivate.FindAgent(ExecuteData.AgentInfo.SessionId);

        Executor = ExecuteAgent.AgentInfo.Name;
        Log.Write("Executor: " + Executor);
        Log.Write("Director: " + Director);
        if (Executor == Director)
        {
            if (data.Message == MoveEvent[0])
            {
                LocalTeleport(0, data);
            }
            else if (data.Message == MoveEvent[1])
            {
                LocalTeleport(1, data);
            }
            else if (data.Message == MoveEvent[2])
            {
                LocalTeleport(2, data);
            }
            else if (data.Message == MoveEvent[3])
            {
                LocalTeleport(3, data);
            }
            else if (data.Message == MoveEvent[4])
            {
                LocalTeleport(4, data);
            }
            else if (data.Message == MoveEvent[5])
            {
                LocalTeleport(5, data);
            }
            else if (data.Message == MoveEvent[6])
            {
                LocalTeleport(6, data);
            }
            else if (data.Message == MoveEvent[7])
            {
                LocalTeleport(7, data);
            }
            else if (data.Message == MoveEvent[8])
            {
                LocalTeleport(8, data);
            }
            else if (data.Message == MoveEvent[9])
            {
                LocalTeleport(9, data);
            }
            else if (data.Message == MoveEvent[10])
            {
                LocalTeleport(10, data);
            }
            else if (data.Message == MoveEvent[11])
            {
                LocalTeleport(11, data);
            }
            else if (data.Message == MoveEvent[12])
            {
                LocalTeleport(12, data);
            }
            else if (data.Message == MoveEvent[13])
            {
                LocalTeleport(13, data);
            }
            else if (data.Message == MoveEvent[14])
            {
                LocalTeleport(14, data);
            }
            else if (data.Message == MoveEvent[15])
            {
                LocalTeleport(15, data);
            }
            else if (data.Message == MoveEvent[16])
            {
                LocalTeleport(16, data);
            }
            else if (data.Message == MoveEvent[17])
            {
                LocalTeleport(17, data);
            }
        }
    }
Beispiel #30
0
    public override void Init()
    {
        // Displays all the registered chat commands
        ChatCommands[HelpCmd] = new ChatCommand
        {
            Action = (String s, AgentPrivate AgentPrivate) =>
            {
                StringBuilder builder = new StringBuilder();
                foreach (KeyValuePair <string, ChatCommand> handler in ChatCommands)
                {
                    builder.AppendFormat($"\n{handler.Key} : {handler.Value.Description}");
                }

                AgentPrivate.SendChat(builder.ToString());
            },
            Description = "Display this message."
        };


        // Displays the ExperienceInfo fields
        ChatCommands[ExpInfoCmd] = new ChatCommand
        {
            Action = (String s, AgentPrivate AgentPrivate) =>
            {
                StringBuilder builder = new StringBuilder();

                // Small action which only adds values that are not empty
                Action <string, object> append = (string name, object value) =>
                {
                    if (value != null && value.ToString().Length > 0)
                    {
                        builder.Append($"\n{name} {value.ToString()}");
                    }
                };

                // Add all the properties to the chat message
                SceneInfo info = ScenePrivate.SceneInfo;
                append("This experience is running build", info.BuildId);
                append("AvatarId", info.AvatarId);
                append("AccessGroup", info.AccessGroup);
                append("CompatVersion", info.CompatVersion);
                append("ProtoVersion", info.ProtoVersion);
                append("Configuration", info.Configuration);
                append("ExperienceId", info.ExperienceId);
                append("Experience", info.ExperienceName);
                append("LocationHandle", info.LocationHandle);
                append("InstanceId", info.InstanceId);
                append("LocationUri", info.SansarUri);
                append("Owner AvatarUuid", info.AvatarUuid);

                AgentPrivate.SendChat(builder.ToString());
            },
            Description = "Dumps the experience info object."
        };

        // Lists all agents currently in the scene
        ChatCommands[ListAgentsCmd] = new ChatCommand
        {
            Action = (String s, AgentPrivate AgentPrivate) =>
            {
                AgentPrivate.SendChat($"There are {ScenePrivate.AgentCount.ToString()} agents in the region.");

                // Build up a list of agents to send to the dialog.
                // The list is built up outside the coroutine as the dialog may be up for some
                // time and the list may change while it is being show.
                List <string> agents = new List <string>();
                foreach (var agent in ScenePrivate.GetAgents())
                {
                    agents.Add($"[{agent.AgentInfo.SessionId.ToString()}:{agent.AgentInfo.AvatarUuid}] {agent.AgentInfo.Name}");
                }

                StartCoroutine(ListAgents, agents, 10, AgentPrivate);
            },
            Description = "List all agents in the region."
        };

        // Report the current agent position
        ChatCommands[MyPosCmd] = new ChatCommand
        {
            Action = (String message, AgentPrivate AgentPrivate) =>
            {
                ObjectPrivate obj = ScenePrivate.FindObject(AgentPrivate.AgentInfo.ObjectId);
                if (obj != null)
                {
                    AgentPrivate.SendChat($"You are at {obj.Position}");
                }
                else
                {
                    AgentPrivate.SendChat($"Where are you? Can not find your avatar object.");
                }
            },
            Description = "Get your current position in world coordinates."
        };

        ScenePrivate.Chat.Subscribe(0, Chat.User, OnChat);
    }