Esempio n. 1
0
    public int WriteAllEmbeddedBehaviorsToDirectory(string dir)
    {
        var allUris = from e in this.db.behaviors.GetAll()
                      select BehaviorSystem.IdToEmbeddedBehaviorUri(e.id);

        return(WriteEmbeddedBehaviorsToDirectory(allUris, dir));
    }
Esempio n. 2
0
    public int WriteEmbeddedBehaviorsToDirectory(IEnumerable <string> behaviorUris, string path)
    {
        int count = 0;

        foreach (string uri in behaviorUris)
        {
            string             id                = BehaviorSystem.GetIdOfBehaviorUri(uri);
            Behaviors.Behavior behavior          = GetBehaviorData(uri);
            BehaviorCards.CardMetadata.Data meta = BehaviorCards.CardMetadata.GetMetaDataFor(behavior);
            string fileName = String.Join("_",
                                          meta.title.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            string baseBehaviorDir = Path.Combine(path, fileName);
            string behaviorDir     = baseBehaviorDir;
            int    i = 1;
            while (Directory.Exists(behaviorDir))
            {
                behaviorDir = baseBehaviorDir + " " + i;
                i++;
            }
            Directory.CreateDirectory(behaviorDir);
            Behaviors.Behavior.WriteToDirectory(behaviorDir, id, behavior);
            count++;
        }
        return(count);
    }
    public AssignedBehavior AddBehavior(UnassignedBehavior behavior)
    {
        OnBeforeAnyChange();
        Debug.Assert(!behavior.behaviorUri.IsNullOrEmpty());

        string finalBehaviorUri = behavior.behaviorUri;

        // Alright, some special logic here. If it's a user-library behavior, do not
        // just use the URI directly. Import it, so turn it into embedded, then use
        // it. We want VOOS files to be stand-alone, so we can't have any local user
        // library dependencies.
        if (BehaviorSystem.IsUserLibraryBehaviorUri(behavior.behaviorUri))
        {
            Behaviors.Behavior importedBehavior = GetBehaviorSystem().GetBehaviorData(behavior.behaviorUri);
            Debug.Assert(!importedBehavior.userLibraryFile.IsNullOrEmpty());
            string importedId = GetBehaviorSystem().GenerateUniqueId();
            GetBehaviorSystem().PutBehavior(importedId, importedBehavior);
            string importedUri = BehaviorSystem.IdToEmbeddedBehaviorUri(importedId);
            finalBehaviorUri = importedUri;
        }

        // Create the use in the database
        string useId = actor.GetBehaviorSystem().GenerateUniqueId();
        var    brain = GetBrain();

        brain.AddUse(new BehaviorUse
        {
            id                  = useId,
            behaviorUri         = finalBehaviorUri,
            propertyAssignments = new Behaviors.PropertyAssignment[0]
        });
        GetBehaviorSystem().PutBrain(GetBrainId(), brain);

        return(new AssignedBehavior(useId, this));
    }
Esempio n. 4
0
 public void SetMetadataJson(string metadataJson)
 {
     Debug.Assert(IsValid(), "Function called on invalid UnassignedBehavior");
     Behaviors.Behavior behavior = GetBehavior();
     behavior.metadataJson = metadataJson;
     behaviorSystem.PutBehavior(BehaviorSystem.GetIdOfBehaviorUri(behaviorUri), behavior);
 }
 public ActorBehaviorsEditor(string actorId, VoosEngine engine, UndoStack undoStack)
 {
     this.actorId        = actorId;
     this.engine         = engine;
     this.undoStack      = undoStack;
     this.behaviorSystem = actor.GetBehaviorSystem();
 }
Esempio n. 6
0
        /// <summary>
        /// Initializes the <see cref="Komodo.Core.Engine.Graphics.GraphicsManager"/> and all <see cref="Komodo.Core.ECS.Systems.ISystem"/> objects.
        /// </summary>
        public void Initialize()
        {
            GraphicsManager.Initialize();
            DefaultSpriteShader = new BasicEffect(GraphicsManager.GraphicsDeviceManager.GraphicsDevice)
            {
                TextureEnabled     = true,
                VertexColorEnabled = true,
            };
            GraphicsManager.VSync = false;

            CameraSystem.Initialize();
            SoundSystem.Initialize();

            var physicsSystems = PhysicsSystems.ToArray();

            foreach (var system in physicsSystems)
            {
                system.Initialize();
            }
            var render3DSystems = Render3DSystems.ToArray();

            foreach (var system in render3DSystems)
            {
                system.Initialize();
            }
            var render2DSystems = Render2DSystems.ToArray();

            foreach (var system in render2DSystems)
            {
                system.Initialize();
            }

            BehaviorSystem.Initialize();
        }
Esempio n. 7
0
    public void ExportBrain(string brainId, Behaviors.Database destination)
    {
        // Export the brain itself.
        Brain brain = GetBrain(brainId).DeepClone();

        destination.brains.Set(brainId, brain);

        // Export the needed embedded behaviors. Don't need to export builtins -
        // they're always available.

        HashSet <string> exportedEmbeddedBehaviorIds = new HashSet <string>();

        foreach (var use in brain.behaviorUses)
        {
            if (BehaviorSystem.IsEmbeddedBehaviorUri(use.behaviorUri))
            {
                exportedEmbeddedBehaviorIds.Add(GetIdOfBehaviorUri(use.behaviorUri));
            }
        }

        foreach (var behaviorId in exportedEmbeddedBehaviorIds)
        {
            destination.behaviors.Set(behaviorId, db.GetBehavior(behaviorId));
        }
    }
    private void AddDefaultPlayerControlsToPlayerBrain()
    {
        string controlsUri = BehaviorSystem.IdToBuiltinBehaviorUri("Player Controls");

        Behaviors.PropertyAssignment speedProp = new Behaviors.PropertyAssignment {
            propertyName = "Speed", valueJson = "{\"value\":5}"
        };
        if (!behaviors.HasBrain("Player"))
        {
            behaviors.PutBrain("Player", new Behaviors.Brain());
        }
        var playerBrain = behaviors.GetBrain("Player");

        playerBrain.AddUse(new Behaviors.BehaviorUse
        {
            id                  = behaviors.GenerateUniqueId(),
            behaviorUri         = controlsUri,
            propertyAssignments = new Behaviors.PropertyAssignment[] { speedProp }
        });

        if (!behaviors.HasBrain("e04de2718a594fc0afd2cb55bd4fa8dc"))
        {
            behaviors.PutBrain("e04de2718a594fc0afd2cb55bd4fa8dc", new Behaviors.Brain());
        }
        var playerInstBrain = behaviors.GetBrain("e04de2718a594fc0afd2cb55bd4fa8dc");

        playerInstBrain.AddUse(new Behaviors.BehaviorUse
        {
            id                  = behaviors.GenerateUniqueId(),
            behaviorUri         = controlsUri,
            propertyAssignments = new Behaviors.PropertyAssignment[] { speedProp }
        });
    }
Esempio n. 9
0
    // TODO put this in some other class, like BehaviorUtil. I don't want it accessing private functions of system.
    // Returns the new brain ID, and fills out newUseIdsByOldOut with a use-ID map.
    public static string CloneBrain(BehaviorSystem system, string originalBrainId)
    {
        Brain  cloneBrain   = system.GetBrain(originalBrainId).DeepClone();
        string cloneBrainId = system.GenerateUniqueId();

        system.PutBrain(cloneBrainId, cloneBrain);
        return(cloneBrainId);
    }
Esempio n. 10
0
 public string GetId()
 {
     if (BehaviorSystem.IsEmbeddedBehaviorUri(behaviorUri))
     {
         return(BehaviorSystem.GetIdOfBehaviorUri(behaviorUri));
     }
     return(null);
 }
    public void CreateOwnCopyOfBrain()
    {
        Debug.Log($"{actor.GetDisplayName()} ({actor.GetName()}) is cloning its brain to have its own copy");
        string newBrainId = BehaviorSystem.CloneBrain(GetBehaviorSystem(), actor.GetBrainName());

        actor.SetBrainName(newBrainId);
        actor.ApplyBrainNameToClones();
    }
Esempio n. 12
0
        public void MockBuilder_BuildFromXml_MockCountTree()
        {
            var system     = new BehaviorSystem();
            var blackBoard = new MockBlackBoard();
            var builder    = new MockBuilder(system, blackBoard);
            var root       = builder.BuildFromXml("../../../MockCountTree.xml");

            Assert.NotNull(root);
        }
Esempio n. 13
0
        private void CreateSystems()
        {
            var behaviorCollationSystem = new BehaviorSystem(TestConfiguration.CellColumnCount, TestConfiguration.CellRowCount, Physics.SpatialHashCellSize);

            AddEntityProcessor(behaviorCollationSystem);
            //AddEntityProcessor(new BehaviorSystem());
            AddEntityProcessor(new BoidsSystem(behaviorCollationSystem));
            AddEntityProcessor(new MoveSystem());
        }
Esempio n. 14
0
    public void ImportLocalByPath(string[] paths)
    {
        string path = paths.First();

        if (path.IsNullOrEmpty())
        {
            return;
        }
        OnBehaviorsLoaded(BehaviorSystem.LoadEmbeddedBehaviorsFromDirectory(path));
    }
Esempio n. 15
0
        protected internal override void OnManagedStart()
        {
            if (hasBehavior)
            {
                this.behavior = BehaviorSystem.InitializeSystemInstance(this, this.behavior);
            }

            this.OnAgentStart();
            currentState = State.Idle;
        }
Esempio n. 16
0
            /// <summary>
            /// Initializes an instance of this system, unique for the given agent
            /// </summary>
            /// <param name="agent"></param>
            /// <param name="system"></param>
            public static BehaviorSystem InitializeSystemInstance(Agent agent, BehaviorSystem system)
            {
                if (!agentBehaviors.ContainsKey(agent))
                {
                    agentBehaviors.Add(agent, system.Instantiate(agent));
                }

                BehaviorSystem instance = agentBehaviors[agent];

                instance.InitializeSystem();
                return(instance);
            }
Esempio n. 17
0
        public void GarbageCollect(bool removeUnusedBehaviors, HashSet <string> usedBrainIds)
        {
            brains.DeleteAll(brains.ComplementOf(usedBrainIds).ToList());

            if (removeUnusedBehaviors)
            {
                HashSet <string> usedEmbeddedBehaviors = new HashSet <string>(
                    usedBrainIds.SelectMany(brainId => GetBrain(brainId).behaviorUses.Select(use => use.behaviorUri)).
                    Where(uri => BehaviorSystem.IsEmbeddedBehaviorUri(uri)).
                    Select(uri => BehaviorSystem.GetIdOfBehaviorUri(uri)));

                behaviors.DeleteAll(behaviors.ComplementOf(usedEmbeddedBehaviors).ToList());
            }
        }
Esempio n. 18
0
    public UnassignedBehavior MakeCopy()
    {
        Behaviors.Behavior behavior   = GetBehavior();
        string             behaviorId = behaviorSystem.GenerateUniqueId();

        Debug.Log(behavior.label + ", " + behavior.metadataJson + ", " + behavior.javascript);
        behaviorSystem.PutBehavior(behaviorId, new Behaviors.Behavior
        {
            label        = behavior.label,
            metadataJson = behavior.metadataJson,
            javascript   = behavior.javascript
        });
        return(new UnassignedBehavior(BehaviorSystem.IdToEmbeddedBehaviorUri(behaviorId), behaviorSystem));
    }
Esempio n. 19
0
    public void Setup()
    {
        Util.FindIfNotSet(this, ref behaviorSystem);
        resourceClaimer.Setup();
        contentController.Setup();

        behaviorSystem.onBehaviorDelete += (deleteEvent) =>
        {
            if (gameObject.activeSelf && BehaviorSystem.IdToEmbeddedBehaviorUri(deleteEvent.id) == cardUri)
            {
                Open(null);
            }
        };
    }
Esempio n. 20
0
        /// <summary>
        /// Updates <see cref="Komodo.Core.ECS.Systems.ISystem"/> objects.
        /// </summary>
        /// <param name="gameTime">Time passed since last <see cref="Update(GameTime)"/>.</param>
        public void Update(GameTime gameTime)
        {
            InputManager.Update();

            BehaviorSystem.PreUpdate(gameTime);
            CameraSystem.PreUpdate(gameTime);
            SoundSystem.PreUpdate(gameTime);
            var physicsSystems = PhysicsSystems.ToArray();

            foreach (var system in physicsSystems)
            {
                system.PreUpdate(gameTime);
            }
            var render3DSystems = Render3DSystems.ToArray();

            foreach (var system in render3DSystems)
            {
                system.PreUpdate(gameTime);
            }
            var render2DSystems = Render2DSystems.ToArray();

            foreach (var system in render2DSystems)
            {
                system.PreUpdate(gameTime);
            }

            BehaviorSystem.UpdateComponents(gameTime);
            CameraSystem.UpdateComponents(gameTime);
            SoundSystem.UpdateComponents(gameTime);
            foreach (var system in physicsSystems)
            {
                system.UpdateComponents(gameTime);
            }

            BehaviorSystem.PostUpdate(gameTime);
            CameraSystem.PostUpdate(gameTime);
            SoundSystem.PostUpdate(gameTime);
            foreach (var system in physicsSystems)
            {
                system.PostUpdate(gameTime);
            }
            foreach (var system in render3DSystems)
            {
                system.PostUpdate(gameTime);
            }
            foreach (var system in render2DSystems)
            {
                system.PostUpdate(gameTime);
            }
        }
Esempio n. 21
0
    public void SetDraftCode(string s)
    {
        Debug.Assert(IsValid(), "Function called on invalid UnassignedBehavior");
        Behaviors.Behavior behavior = GetBehavior();

        if (behavior.draftJavascript == s)
        {
            Debug.Log("No actual change to draft behavior code. Doing nothing.");
            return;
        }

        behavior.draftJavascript = s;
        behaviorSystem.PutBehavior(BehaviorSystem.GetIdOfBehaviorUri(behaviorUri), behavior);
    }
    public UnassignedBehavior CreateNewBehavior(string initCode, string metadataJson)
    {
        string behaviorId = GetBehaviorSystem().GenerateUniqueId();

        GetBehaviorSystem().PutBehavior(behaviorId, new Behaviors.Behavior
        {
            label        = "Custom",
            metadataJson = metadataJson,
            javascript   = initCode
        });

        UnassignedBehavior newBehavior = new UnassignedBehavior(BehaviorSystem.IdToEmbeddedBehaviorUri(behaviorId), GetBehaviorSystem());

        // NOTE: We don't need to add it here, per se. The caller should call AddBehavior on us with this instance.
        return(newBehavior);
    }
Esempio n. 23
0
        /// <summary>
        /// Creates the Game instance, instantiating the underlying <see cref="Komodo.Core.MonoGame"/> instance, <see cref="Komodo.Core.Engine.Graphics.GraphicsManager"/>, and <see cref="Komodo.Core.ECS.Systems.ISystem"/> objects.
        /// </summary>
        public Game()
        {
            _monoGame       = new MonoGame(this);
            GraphicsManager = new GraphicsManager(this)
            {
                IsMouseVisible = true
            };

            Content = _monoGame.Content;

            BehaviorSystem  = new BehaviorSystem(this);
            CameraSystem    = new CameraSystem(this);
            PhysicsSystems  = new List <PhysicsSystem>();
            Render2DSystems = new List <Render2DSystem>();
            Render3DSystems = new List <Render3DSystem>();
            SoundSystem     = new SoundSystem(this);
        }
Esempio n. 24
0
        public void MockBuilder_BuildFromXml_CountMatch(int count)
        {
            var system     = new BehaviorSystem();
            var blackBoard = new MockBlackBoard();
            var builder    = new MockBuilder(system, blackBoard);
            var root       = builder.BuildFromXml("../../../MockCountTree.xml");

            root.Enter();
            for (int i = 0; i < count; i++)
            {
                system.Step(1f);
            }
            var mockCount = blackBoard.GetInt("count");

            Console.WriteLine($"the count is: {mockCount}");
            Assert.AreEqual((count - 1) / 3, mockCount);
        }
Esempio n. 25
0
    private void ReloadCard(string path)
    {
        string metaPath = path + ".metaJson";

        if (!File.Exists(metaPath))
        {
            Complain($"Can't load card from {path} because there is no corresponding .metaJson file.");
            return;
        }
        string jsContents   = File.ReadAllText(path);
        string metaContents = File.ReadAllText(metaPath);

        BehaviorCards.CardMetadata cardMeta = JsonUtility.FromJson <BehaviorCards.CardMetadata>(metaContents);
        string providedId = cardMeta.cardSystemCardData.userProvidedId;

        if (!string.IsNullOrEmpty(cardMeta.cardSystemCardData.imageResourcePath) &&
            !cardMeta.cardSystemCardData.imageResourcePath.StartsWith("icon:") &&
            !cardMeta.cardSystemCardData.imageResourcePath.StartsWith("BuiltinAssets")
            )
        {
            Complain($"Error loading {path}: metaJson file has invalid format for imageResourcePath field.");
            return;
        }
        if (string.IsNullOrEmpty(providedId))
        {
            Complain($"Error loading {path}: metaJson file is missing userProvidedId field.");
            return;
        }
        providedId = providedId.ToLowerInvariant();
        if (!BehaviorSystem.IsGuid(providedId))
        {
            Complain($"Error loading {path}: userProvidedId must be a valid GUID (32 hex digits).");
            return;
        }
        Debug.Log($"Hot-loading card from {path} -> {providedId}");
        Behavior behavior = new Behavior
        {
            label        = "Hotloaded",
            javascript   = jsContents,
            metadataJson = metaContents
        };

        loadedCardGuids.Add(providedId);
        behaviorSystem.PutBehavior(providedId, behavior);
    }
Esempio n. 26
0
    public IEnumerator Setup()
    {
        TestUtil.TestScene scene = new TestUtil.TestScene("main");
        yield return(scene.LoadAndWait());

        behaviorSystem = scene.FindRootComponent <BehaviorSystem>("ScriptingSystems");
        voosEngine     = scene.FindRootComponent <VoosEngine>("ScriptingSystems");

        // Wait for loading done..
        while (true)
        {
            if (voosEngine.GetIsRunning())
            {
                yield break;
            }
            yield return(null);
        }
    }
Esempio n. 27
0
    private void ImportLocal()
    {
#if USE_FILEBROWSER
        var paths = Crosstales.FB.FileBrowser.OpenFolders("Open folder", null);
        if (paths.Count() == 0)
        {
            return;
        }
        string path = paths.First();
        if (path.IsNullOrEmpty())
        {
            return;
        }
        OnBehaviorsLoaded(BehaviorSystem.LoadEmbeddedBehaviorsFromDirectory(path));
#else
        popups.Show("Use the console command 'importcards C:\\path\\to\\cardfolder' instead. Or, build with the free CrossTales FileBrowser plugin.", "OK");
#endif
    }
Esempio n. 28
0
    public void AcceptClickedLibraryCard(Card card, CardContainer targetContainer, CardDeck targetSlot)
    {
        Card newCard = null;

        if (targetContainer != null)
        {
            newCard = targetContainer.ReplaceCard(card.GetModel());
        }
        else
        {
            newCard = targetSlot.AcceptCard(card.GetModel());

            string uri = newCard.GetCardAssignment().GetCard().GetUri();
            if (BehaviorSystem.IsBuiltinBehaviorUri(uri))
            {
            }
        }
        OnNewCardAdded(newCard);
    }
Esempio n. 29
0
    private void OnBehaviorPut(BehaviorSystem.PutEvent putEvent)
    {
        if (!IsOpen())
        {
            return;
        }

        if (putEvent.isNewBehavior)
        {
            GameObject containerObj = CreateCardAndContainer();
            PopulateContainerWithUri(containerObj, BehaviorSystem.IdToEmbeddedBehaviorUri(putEvent.id));
            StartCoroutine(ScrollToAndFlash(containerObj));
            CardContainer container = containerObj.GetComponentInChildren <CardContainer>();
            containerObj.SetActive(DoesCardMatchSearch(container.GetCard(), cardLibraryUI.inputField.text));
            if (selection != null)
            {
                StartSelectionForContainerObj(containerObj);
            }
        }
        else
        {
            foreach (GameObject containerObj in cardContainerObjects)
            {
                CardContainer container = containerObj.GetComponentInChildren <CardContainer>();
                if (container.GetCard().GetModel().GetId() == putEvent.id)
                {
                    PopulateContainerWithUri(containerObj, BehaviorSystem.IdToEmbeddedBehaviorUri(putEvent.id));
                    break;
                }
            }
        }

        if (cardDetail.IsOpen() && cardDetail.IsModelValid() && cardDetail.GetModel().GetId() == putEvent.id)
        {
            cardDetail.Populate(
                new BehaviorCards.UnassignedCard(new UnassignedBehavior(
                                                     BehaviorSystem.IdToEmbeddedBehaviorUri(putEvent.id), behaviorSystem)));
        }
    }
Esempio n. 30
0
    static void CommandFindJs(CommandArg[] args)
    {
        try
        {
            if (args.Length == 0)
            {
                Log($"Usage: findjs some word or phrase");
                return;
            }
            string q = String.Join(" ", args.Select(a => a.String)).ToLowerInvariant();
            Log($"Searching for \"{q}\"");
            foreach (var cardUri in main.behaviorSystem.GetCards())
            {
                if (!BehaviorSystem.IsEmbeddedBehaviorUri(cardUri))
                {
                    continue;
                }
                var data = main.behaviorSystem.GetBehaviorData(cardUri);
                if (data.javascript.ToLowerInvariant().Contains(q))
                {
                    var cardMd = BehaviorCards.CardMetadata.GetMetaDataFor(data);

                    foreach (var line in data.javascript.EnumerateNumberedLines())
                    {
                        if (line.line.ToLowerInvariant().Contains(q))
                        {
                            Log($"<color=#888888>{cardMd.title}:{line.number}</color> {line.line}");
                        }
                    }
                }
            }
        }
        catch (System.Exception e)
        {
            Log($"Failed with exception: {e}");
            Log($"Usage: findjs 'some word or phrase'");
        }
    }