public void TestSort()
        {
            var slowId        = new ActorId("slow");
            var fastId        = new ActorId("fast");
            var standardId    = new ActorId("Standard");
            var slowerActor   = CreateActor.Do(slowId, new Speed(49));
            var fasterActor   = CreateActor.Do(fastId, new Speed(51));
            var standardActor = CreateActor.Do(standardId, new Speed(50));

            var actorRepository = new Mock <IActorRepository>();

            actorRepository.Setup(
                repo => repo.FindIn(It.IsAny <IEnumerable <ActorId> >()))
            .Returns(new[] { slowerActor, fasterActor, standardActor });

            var sortService = new SortBySpeedService(actorRepository.Object);

            var result   = sortService.Sort(new[] { slowId, fastId, standardId });
            var expected = new List <ActorId> {
                fastId, standardId, slowId
            };

            Assert.AreEqual(expected.Count, result.Count);
            Assert.IsTrue(expected.SequenceEqual(result));
        }
        private void SendCreateActorResponse(CreateActor originalMessage, IList <Actor> actors = null, string failureMessage = null, Action onCompleteCallback = null)
        {
            Trace trace = new Trace()
            {
                Severity = (actors != null) ? TraceSeverity.Info : TraceSeverity.Error,
                Message  = (actors != null) ?
                           $"Successfully created {actors?.Count ?? 0} objects." :
                           failureMessage
            };

            Protocol.Send(new ObjectSpawned()
            {
                Result = new OperationResult()
                {
                    ResultCode = (actors != null) ? OperationResultCode.Success : OperationResultCode.Error,
                    Message    = trace.Message
                },

                Traces = new List <Trace>()
                {
                    trace
                },
                Actors = actors?.Select((actor) => actor.GenerateInitialPatch()) ?? new ActorPatch[] { }
            },
                          originalMessage.MessageId);

            onCompleteCallback?.Invoke();
        }
        public void Can_change_actors_password()
        {
            var createActor = new CreateActor
            {
                ActorId  = Guid.NewGuid(),
                Password = TestDataGenerator.GetRandomString(),
                Username = TestDataGenerator.GetRandomString()
            };

            _authCommands.CreateActor(createActor);

            var actor             = _authRepository.Actors.Single(a => a.Id == createActor.ActorId);
            var encryptedPassword = actor.EncryptedPassword;

            var changePassword = new ChangePassword
            {
                ActorId     = createActor.ActorId,
                NewPassword = TestDataGenerator.GetRandomString()
            };

            _authCommands.ChangePassword(changePassword);

            actor = _authRepository.Actors.Single(a => a.Id == createActor.ActorId);

            actor.EncryptedPassword.Should().NotBe(encryptedPassword);
        }
Beispiel #4
0
 public void EnableActor(bool enableActor, string actorName, CreateActor creator)
 {
     lock (PhysicalActors)
     {
         BSActor theActor;
         if (PhysicalActors.TryGetActor(actorName, out theActor))
         {
             // The actor already exists so just turn it on or off
             DetailLog("{0},BSPhysObject.EnableActor,enablingExistingActor,name={1},enable={2}", LocalID, actorName, enableActor);
             theActor.Enabled = enableActor;
         }
         else
         {
             // The actor does not exist. If it should, create it.
             if (enableActor)
             {
                 DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName);
                 theActor = creator();
                 PhysicalActors.Add(actorName, theActor);
                 theActor.Enabled = true;
             }
             else
             {
                 DetailLog("{0},BSPhysObject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName);
             }
         }
     }
 }
        public async Task <Actor> Create(CreateActor data,
                                         [Service] IActorRepository repository,
                                         [Service] ICountryRepository countries)
        {
            var country = await countries.GetByIso(data.Nationality);

            var actor = new Actor(data.Name, data.DateOfBirth, country);
            await repository.Add(actor);

            return(actor);
        }
        private void ProcessCreatedActors(CreateActor originalMessage, IList <Actor> createdActors, Action onCompleteCallback)
        {
            var guids     = new DeterministicGuids(originalMessage.Actor?.Id);
            var rootActor = createdActors.FirstOrDefault();

            if (rootActor.transform.parent == null)
            {
                // Delete entire hierarchy as we no longer have a valid parent actor for the root of this hierarchy.  It was likely
                // destroyed in the process of the async operation before this callback was called.
                foreach (var actor in createdActors)
                {
                    actor.Destroy();
                }

                createdActors.Clear();

                SendCreateActorResponse(
                    originalMessage,
                    failureMessage: "Parent for the actor being created no longer exists.  Cannot create new actor.");
                return;
            }

            ProcessActors(rootActor.transform, rootActor.transform.parent.GetComponent <Actor>());

            rootActor?.ApplyPatch(originalMessage.Actor);
            Actor.ApplyVisibilityUpdate(rootActor);

            _actorManager.UponStable(
                () => SendCreateActorResponse(originalMessage, actors: createdActors, onCompleteCallback: onCompleteCallback));

            void ProcessActors(Transform xfrm, Actor parent)
            {
                // Generate actors for all GameObjects, even if the loader didn't. Only loader-generated
                // actors are returned to the app though. We do this so library objects get enabled/disabled
                // correctly, even if they're not tracked by the app.
                var actor = xfrm.gameObject.GetComponent <Actor>() ?? xfrm.gameObject.AddComponent <Actor>();

                _actorManager.AddActor(guids.Next(), actor);
                _ownedGameObjects.Add(actor.gameObject);

                actor.ParentId = parent?.Id ?? actor.ParentId;
                if (actor.Renderer != null)
                {
                    actor.MaterialId = MREAPI.AppsAPI.AssetCache.GetId(actor.Renderer.sharedMaterial) ?? Guid.Empty;
                    actor.MeshId     = MREAPI.AppsAPI.AssetCache.GetId(actor.UnityMesh) ?? Guid.Empty;
                }

                foreach (Transform child in xfrm)
                {
                    ProcessActors(child, actor);
                }
            }
        }
Beispiel #7
0
        public void Empty_password_is_not_valid_for_actor_creation()
        {
            var model = new CreateActor
            {
                ActorId  = Guid.NewGuid(),
                Password = string.Empty,
                Username = TestDataGenerator.GetRandomString()
            };

            var result = _authQueries.GetValidationResult(model);

            result.IsValid.Should().BeFalse();
            result.Errors.Single().ErrorMessage.Should().Be(ErrorsCodes.PasswordIsEmpty.ToString());
        }
Beispiel #8
0
        public void CreateActor(CreateActor model)
        {
            var result = _authQueries.GetValidationResult(model);

            if (result.IsValid == false)
            {
                throw new ApplicationException(result.Errors.First().ErrorMessage);
            }

            var actor = new Entities.Actor(model.ActorId, model.Username, model.Password);

            _repository.Actors.Add(actor.Data);
            _repository.SaveChanges();
        }
Beispiel #9
0
        public void Duplicate_actorId_is_not_valid_for_actor_creation()
        {
            var model = new CreateActor
            {
                ActorId  = Guid.NewGuid(),
                Password = TestDataGenerator.GetRandomString(),
                Username = TestDataGenerator.GetRandomString()
            };

            _authCommands.CreateActor(model);

            var result = _authQueries.GetValidationResult(model);

            result.IsValid.Should().BeFalse();
            result.Errors.Single().ErrorMessage.Should().Be(ErrorsCodes.ActorAlreadyCreated.ToString());
        }
        public void Can_create_actor()
        {
            var model = new CreateActor
            {
                ActorId  = Guid.NewGuid(),
                Username = TestDataGenerator.GetRandomString(),
                Password = TestDataGenerator.GetRandomString()
            };

            _authCommands.CreateActor(model);

            var actor = _authRepository.Actors.SingleOrDefault(a => a.Id == model.ActorId);

            actor.Should().NotBeNull();
            actor.Username.Should().Be(model.Username);
            actor.EncryptedPassword.Should().NotBeNullOrWhiteSpace();
        }
        private void ProcessCreatedActors(CreateActor originalMessage, IList <Actor> createdActors, Action onCompleteCallback)
        {
            var guids     = new DeterministicGuids(originalMessage.Actor?.Id);
            var rootActor = createdActors.FirstOrDefault();

            ProcessActors(rootActor.transform, rootActor.transform.parent.GetComponent <Actor>());

            rootActor?.ApplyPatch(originalMessage.Actor);
            Actor.ApplyVisibilityUpdate(rootActor);

            foreach (var actor in createdActors)
            {
                actor.AddSubscriptions(originalMessage.Subscriptions);
            }

            SendCreateActorResponse(originalMessage, actors: createdActors, onCompleteCallback: onCompleteCallback);

            void ProcessActors(Transform xfrm, Actor parent)
            {
                // Generate actors for all GameObjects, even if the loader didn't. Only loader-generated
                // actors are returned to the app though. We do this so library objects get enabled/disabled
                // correctly, even if they're not tracked by the app.
                var actor = xfrm.gameObject.GetComponent <Actor>() ?? xfrm.gameObject.AddComponent <Actor>();

                _actorManager.AddActor(guids.Next(), actor);
                _ownedGameObjects.Add(actor.gameObject);

                actor.ParentId = parent?.Id ?? actor.ParentId;
                if (actor.Renderer != null)
                {
                    actor.MaterialId = MREAPI.AppsAPI.AssetCache.GetId(actor.Renderer.sharedMaterial) ?? Guid.Empty;
                }

                foreach (Transform child in xfrm)
                {
                    ProcessActors(child, actor);
                }
            }
        }
Beispiel #12
0
        public void Same_passwords_are_not_valid_for_password_change()
        {
            var createActor = new CreateActor
            {
                ActorId  = Guid.NewGuid(),
                Password = TestDataGenerator.GetRandomString(),
                Username = TestDataGenerator.GetRandomString()
            };

            _authCommands.CreateActor(createActor);

            var changePassword = new ChangePassword
            {
                ActorId     = createActor.ActorId,
                NewPassword = createActor.Password
            };

            var result = _authQueries.GetValidationResult(changePassword);

            result.IsValid.Should().BeFalse();
            result.Errors.Single().ErrorMessage.Should().Be(ErrorsCodes.PasswordsMatch.ToString());
        }
 public void EnableActor(bool enableActor, string actorName, CreateActor creator)
 {
     lock (PhysicalActors)
     {
         BSActor theActor;
         if (PhysicalActors.TryGetActor(actorName, out theActor))
         {
             // The actor already exists so just turn it on or off
             theActor.Enabled = enableActor;
         }
         else
         {
             // The actor does not exist. If it should, create it.
             if (enableActor)
             {
                 theActor = creator();
                 PhysicalActors.Add(actorName, theActor);
                 theActor.Enabled = true;
             }
         }
     }
 }
Beispiel #14
0
        public void Invalid_roleId_is_not_valid_for_role_assignment()
        {
            var createActor = new CreateActor
            {
                ActorId  = Guid.NewGuid(),
                Username = TestDataGenerator.GetRandomString(),
                Password = TestDataGenerator.GetRandomString()
            };

            _authCommands.CreateActor(createActor);

            var assignRole = new AssignRole
            {
                ActorId = createActor.ActorId,
                RoleId  = Guid.NewGuid()
            };

            var result = _authQueries.GetValidationResult(assignRole);

            result.IsValid.Should().BeFalse();
            result.Errors.Single().ErrorMessage.Should().Be(ErrorsCodes.RoleNotFound.ToString());
        }
Beispiel #15
0
        public void Invalid_password_is_not_valid_for_login()
        {
            var createActor = new CreateActor
            {
                ActorId  = Guid.NewGuid(),
                Password = TestDataGenerator.GetRandomString(),
                Username = TestDataGenerator.GetRandomString()
            };

            _authCommands.CreateActor(createActor);

            var loginActor = new LoginActor
            {
                ActorId  = createActor.ActorId,
                Password = TestDataGenerator.GetRandomString()
            };

            var result = _authQueries.GetValidationResult(loginActor);

            result.IsValid.Should().BeFalse();
            result.Errors.Single().ErrorMessage.Should().Be(ErrorsCodes.ActorPasswordIsNotValid.ToString());
        }
Beispiel #16
0
        public void Can_verify_permission_for_admin()
        {
            _authCommands.CreatePermission(new CreatePermission
            {
                Name   = "Test",
                Module = "Test"
            });
            var permissions = _authQueries.GetPermissions().Select(p => p.Id);
            var roleId      = Guid.NewGuid();

            _authCommands.CreateRole(new CreateRole
            {
                RoleId      = roleId,
                Permissions = permissions.ToList()
            });
            var actorId          = Guid.NewGuid();
            var createActorModel = new CreateActor
            {
                ActorId  = actorId,
                Password = TestDataGenerator.GetRandomString(),
                Username = TestDataGenerator.GetRandomString()
            };

            _authCommands.CreateActor(createActorModel);
            _authCommands.AssignRoleToActor(new AssignRole
            {
                ActorId = createActorModel.ActorId,
                RoleId  = roleId
            });

            var actorHasPermission   = _authQueries.VerifyPermission(actorId, "Test", "Test");
            var actorHasNoPermission = _authQueries.VerifyPermission(actorId, "Invalid", "Invalid");

            actorHasPermission.Should().BeTrue();
            actorHasNoPermission.Should().BeFalse();
        }
        public void Can_assign_role_to_actor()
        {
            var createActor = new CreateActor
            {
                ActorId  = Guid.NewGuid(),
                Username = TestDataGenerator.GetRandomString(),
                Password = TestDataGenerator.GetRandomString()
            };

            _authCommands.CreateActor(createActor);

            _authCommands.CreatePermission(new CreatePermission
            {
                Name   = "Test",
                Module = "Test"
            });

            var createRole = new CreateRole
            {
                RoleId      = Guid.NewGuid(),
                Permissions = _authQueries.GetPermissions().Select(p => p.Id).ToList()
            };

            _authCommands.CreateRole(createRole);

            _authCommands.AssignRoleToActor(new AssignRole
            {
                ActorId = createActor.ActorId,
                RoleId  = createRole.RoleId
            });

            var actor = _authRepository.Actors.Single(a => a.Id == createActor.ActorId);

            actor.Role.Should().NotBeNull();
            actor.Role.Id.Should().Be(createRole.RoleId);
        }
 public void EnableActor(bool enableActor, string actorName, CreateActor creator)
 {
     lock (PhysicalActors)
     {
     BSActor theActor;
     if (PhysicalActors.TryGetActor(actorName, out theActor))
     {
         // The actor already exists so just turn it on or off
         theActor.Enabled = enableActor;
     }
     else
     {
         // The actor does not exist. If it should, create it.
         if (enableActor)
         {
             theActor = creator();
             PhysicalActors.Add(actorName, theActor);
             theActor.Enabled = true;
         }
     }
     }
 }
Beispiel #19
0
 public void EnableActor(bool enableActor, string actorName, CreateActor creator)
 {
     lock (PhysicalActors)
     {
         BSActor theActor;
         if (PhysicalActors.TryGetActor(actorName, out theActor))
         {
             // The actor already exists so just turn it on or off
             DetailLog("{0},BSPhysObject.EnableActor,enableExistingActor,name={1},enable={2}", LocalID, actorName, enableActor);
             theActor.Enabled = enableActor;
         }
         else
         {
             // The actor does not exist. If it should, create it.
             if (enableActor)
             {
                 DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName);
                 theActor = creator();
                 PhysicalActors.Add(actorName, theActor);
                 theActor.Enabled = true;
             }
             else
             {
                 DetailLog("{0},BSPhysobject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName);
             }
         }
     }
 }
        private void ProcessCreatedActors(CreateActor originalMessage, IList <Actor> createdActors, Action onCompleteCallback, string guidSeed = null)
        {
            Guid guidGenSeed;

            if (originalMessage != null)
            {
                guidGenSeed = originalMessage.Actor.Id;
            }
            else
            {
                guidGenSeed = UtilMethods.StringToGuid(guidSeed);
            }
            var guids = new DeterministicGuids(guidGenSeed);

            // find the actors with no actor parents
            var rootActors = GetDistinctTreeRoots(
                createdActors.Select(a => a.gameObject).ToArray()
                ).Select(go => go.GetComponent <Actor>()).ToArray();

            var rootActor    = createdActors.FirstOrDefault();
            var createdAnims = new List <Animation.BaseAnimation>(5);

            if (rootActors.Length == 1 && rootActor.transform.parent == null)
            {
                // Delete entire hierarchy as we no longer have a valid parent actor for the root of this hierarchy.  It was likely
                // destroyed in the process of the async operation before this callback was called.
                foreach (var actor in createdActors)
                {
                    actor.Destroy();
                }

                createdActors.Clear();

                SendCreateActorResponse(
                    originalMessage,
                    failureMessage: "Parent for the actor being created no longer exists.  Cannot create new actor.");
                return;
            }

            var secondPassXfrms = new List <Transform>(2);

            foreach (var root in rootActors)
            {
                ProcessActors(root.transform, root.transform.parent != null ? root.transform.parent.GetComponent <Actor>() : null);
            }
            // some things require the whole hierarchy to have actors on it. run those here
            foreach (var pass2 in secondPassXfrms)
            {
                ProcessActors2(pass2);
            }

            if (originalMessage != null && rootActors.Length == 1)
            {
                rootActor?.ApplyPatch(originalMessage.Actor);
            }
            Actor.ApplyVisibilityUpdate(rootActor);

            _actorManager.UponStable(
                () => SendCreateActorResponse(originalMessage, actors: createdActors, anims: createdAnims, onCompleteCallback: onCompleteCallback));

            void ProcessActors(Transform xfrm, Actor parent)
            {
                // Generate actors for all GameObjects, even if the loader didn't. Only loader-generated
                // actors are returned to the app though. We do this so library objects get enabled/disabled
                // correctly, even if they're not tracked by the app.
                var actor = xfrm.gameObject.GetComponent <Actor>() ?? xfrm.gameObject.AddComponent <Actor>();

                _actorManager.AddActor(guids.Next(), actor);
                _ownedGameObjects.Add(actor.gameObject);

                actor.ParentId = parent?.Id ?? actor.ParentId;
                if (actor.Renderer != null)
                {
                    actor.MaterialId = AssetCache.GetId(actor.Renderer.sharedMaterial) ?? Guid.Empty;
                    actor.MeshId     = AssetCache.GetId(actor.UnityMesh) ?? Guid.Empty;
                }

                // native animation construction requires the whole actor hierarchy to already exist. defer to second pass
                var nativeAnim = xfrm.gameObject.GetComponent <UnityEngine.Animation>();

                if (nativeAnim != null && createdActors.Contains(actor))
                {
                    secondPassXfrms.Add(xfrm);
                }

                foreach (Transform child in xfrm)
                {
                    ProcessActors(child, actor);
                }
            }

            void ProcessActors2(Transform xfrm)
            {
                var actor      = xfrm.gameObject.GetComponent <Actor>();
                var nativeAnim = xfrm.gameObject.GetComponent <UnityEngine.Animation>();

                if (nativeAnim != null && createdActors.Contains(actor))
                {
                    var animTargets = xfrm.gameObject.GetComponent <PrefabAnimationTargets>();
                    int stateIndex  = 0;
                    foreach (AnimationState state in nativeAnim)
                    {
                        var anim = new NativeAnimation(AnimationManager, guids.Next(), nativeAnim, state);
                        anim.TargetIds = animTargets != null
                                                        ? animTargets.GetTargets(xfrm, stateIndex ++, addRootToTargets : true).Select(a => a.Id).ToList()
                                                        : new List <Guid>()
                        {
                            actor.Id
                        };

                        AnimationManager.RegisterAnimation(anim);
                        createdAnims.Add(anim);
                    }
                }
            }
        }
        private void ProcessCreatedActors(CreateActor originalMessage, IList <Actor> createdActors, Action onCompleteCallback, string guidSeed = null)
        {
            Guid guidGenSeed;

            if (originalMessage != null)
            {
                guidGenSeed = originalMessage.Actor.Id;
            }
            else
            {
                guidGenSeed = UtilMethods.StringToGuid(guidSeed);
            }
            var guids = new DeterministicGuids(guidGenSeed);

            // find the actors with no actor parents
            var rootActors = GetDistinctTreeRoots(
                createdActors.ToArray()
                ).Select(go => go as Actor).ToArray();
            var rootActor    = createdActors.FirstOrDefault();
            var createdAnims = new List <Animation.BaseAnimation>(5);

            if (rootActors.Length == 1 && rootActor.GetParent() == null)
            {
                // Delete entire hierarchy as we no longer have a valid parent actor for the root of this hierarchy.  It was likely
                // destroyed in the process of the async operation before this callback was called.
                foreach (var actor in createdActors)
                {
                    actor.Destroy();
                }

                createdActors.Clear();

                SendCreateActorResponse(
                    originalMessage,
                    failureMessage: "Parent for the actor being created no longer exists.  Cannot create new actor.");
                return;
            }

            var secondPassXfrms = new List <Spatial>(2);

            foreach (var root in rootActors)
            {
                ProcessActors(root.Node3D, root.GetParent() as Actor);
            }
            // some things require the whole hierarchy to have actors on it. run those here
            foreach (var pass2 in secondPassXfrms)
            {
                ProcessActors2(pass2);
            }

            if (originalMessage != null && rootActors.Length == 1)
            {
                rootActor?.ApplyPatch(originalMessage.Actor);
            }
            Actor.ApplyVisibilityUpdate(rootActor);

            _actorManager.UponStable(
                () => SendCreateActorResponse(originalMessage, actors: createdActors, anims: createdAnims, onCompleteCallback: onCompleteCallback));

            void ProcessActors(Spatial node3D, Actor parent)
            {
                // Generate actors for all node3D, even if the loader didn't. Only loader-generated
                // actors are returned to the app though. We do this so library objects get enabled/disabled
                // correctly, even if they're not tracked by the app.
                Actor actor = (node3D as Actor) ?? Actor.Instantiate(node3D);

                _actorManager.AddActor(guids.Next(), actor);
                _ownedNodes.Add(actor);

                actor.ParentId = parent?.Id ?? actor.ParentId;

                if (actor.MeshInstance != null)
                {
                    // only overwrite material if there's something in the cache, i.e. not a random library material
                    if (actor.MeshInstance.MaterialOverride != null)
                    {
                        var matId = AssetManager.GetByObject(actor.MeshInstance.MaterialOverride)?.Id;
                        if (matId.HasValue)
                        {
                            actor.MaterialId = matId.Value;
                        }
                    }

                    actor.MeshId = AssetManager.GetByObject(actor.GodotMesh)?.Id ?? Guid.Empty;
                }

                // native animation construction requires the whole actor hierarchy to already exist. defer to second pass
                var nativeAnim = node3D.GetChild <Godot.AnimationPlayer>();

                if (nativeAnim != null && createdActors.Contains(actor))
                {
                    secondPassXfrms.Add(node3D);
                }

                foreach (object node in actor.GetChildren())
                {
                    if (node is Spatial)
                    {
                        ProcessActors((Spatial)node, actor);
                    }
                }
            }

            void ProcessActors2(Spatial node3D)
            {
                var actor           = node3D as Actor;
                var animationPlayer = node3D.GetChild <Godot.AnimationPlayer>();

                if (animationPlayer != null && createdActors.Contains(actor))
                {
                    var animTargets = node3D.GetChild <PrefabAnimationTargets>();
                    int animIndex   = 0;
                    foreach (string animationString in animationPlayer.GetAnimationList())
                    {
                        var anim = new NativeAnimation(AnimationManager, guids.Next(), animationPlayer, animationPlayer.GetAnimation(animationString));
                        anim.TargetIds = animTargets != null
                                                        ? animTargets.GetTargets(node3D, animIndex ++, addRootToTargets : true).Select(a => a.Id).ToList()
                                                        : new List <Guid>()
                        {
                            actor.Id
                        };

                        AnimationManager.RegisterAnimation(anim);
                        createdAnims.Add(anim);
                    }
                }
            }
        }
Beispiel #22
0
        public ValidationResult GetValidationResult(CreateActor model)
        {
            var validator = new CreateActorValidator(_repository);

            return(validator.Validate(model));
        }