protected override void OnAssert() { if (this.tree == null) { this.tree = new SerializedTree <BehaviorNode, Behavior>(); this.tree.root.data = Behavior.Instantiate(typeof(Sequence)); } try { this.tree.Assert(); } catch (Exception e) { StratusDebug.Log($"The tree {name} is damaged: '{e.Message}'. Attempting to repair..."); this.tree.Repair(); // Try again try { this.tree.Assert(); } catch (Exception e2) { StratusDebug.Log($"The tree {name} is damaged: '{e.Message}'"); throw e2; } } }
}//end of OnGUI void ClearTreeButton() { if (saveTreeToObject != null) { SerializedTree sTree = saveTreeToObject.GetComponent <SerializedTree>(); sTree.ClearDialogueTree(); } }
private void Initialize(string workingDir, bool createNotFound) { if (String.IsNullOrEmpty(workingDir)) { throw new InvalidOperationException(); } if (!Directory.Exists(workingDir)) { Directory.CreateDirectory(workingDir); } if (_isSystem) { _treeFileName = Path.Combine(workingDir, "SLinkT2.6.10621.1.dat"); _blockFileName = Path.Combine(workingDir, "SLinkB2.6.10621.1.dat"); } else { string tempFile = Path.GetFileNameWithoutExtension( Path.GetTempFileName()); _treeFileName = Path.Combine(workingDir, tempFile + "Tree.dat"); _blockFileName = Path.Combine(workingDir, tempFile + "Block.dat"); } if (File.Exists(_treeFileName) && File.Exists(_blockFileName)) { _isExisted = true; _plusTree = SerializedTree.ReOpen(_treeFileName, _blockFileName); if (_plusTree.ContainsKey("$DataCount$")) { _count = Convert.ToInt32(_plusTree["$DataCount$"]); } } else { _count = 0; if (createNotFound) { _plusTree = SerializedTree.Initialize(_treeFileName, _blockFileName, 64); } } if (_plusTree != null) { _targetCache = new DatabaseTargetCache(100); } }
public void LoadCache() { if (treeCache == null) { if (File.Exists(treefile) && File.Exists(datafile)) { treeCache = new SerializedTree(hBplusTreeBytes.ReOpen(treefile, datafile)); } else { treeCache = new SerializedTree(hBplusTreeBytes.Initialize(treefile, datafile, 500)); } treeCache.SetFootPrintLimit(10); } }
public void LoadCache() { if (_treeCache != null) { return; } if (File.Exists(_treefile) && File.Exists(_datafile)) { _treeCache = new SerializedTree(hBplusTreeBytes.ReOpen(_treefile, _datafile)); } else { _treeCache = new SerializedTree(hBplusTreeBytes.Initialize(_treefile, _datafile, 500)); } _treeCache.SetFootPrintLimit(10); }
protected override void Dispose(bool disposing) { if (_plusTree != null) { try { // Save the system reflection database, if newly created... if (_isSystem) { if (!_isExisted) { // Add some metadata... _plusTree["$DataCount$"] = _count.ToString(); _plusTree["$DataVersion$"] = "2.6.10621.1"; _plusTree.Commit(); } } _plusTree.Shutdown(); _plusTree = null; // For the non-system reflection database, delete after use... if (!_isSystem) { if (!String.IsNullOrEmpty(_treeFileName) && File.Exists(_treeFileName)) { File.Delete(_treeFileName); } if (!String.IsNullOrEmpty(_blockFileName) && File.Exists(_blockFileName)) { File.Delete(_blockFileName); } } } catch { } } }
/// <summary> /// Initializes a new instance of the <see cref="GamePage"/> class. The given package group and node tree are /// wrapped by the page. /// </summary> /// <param name="packageGroup">The package group which the node tree maps to.</param> /// <param name="nodeTree">The prebuilt node tree to display.</param> /// <param name="version">The Warcraft version that the game page is contextually relevant for.</param> /// <param name="alias">The name of the page.</param> public GamePage(PackageGroup packageGroup, SerializedTree nodeTree, WarcraftVersion version, string alias) { this.Alias = alias; _uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); _treeModel = new FileTreeModel(nodeTree); this.GameContext = new WarcraftGameContext(version, packageGroup, _treeModel); _treeAlignment = new Alignment(0.5f, 0.5f, 1.0f, 1.0f) { TopPadding = 1, BottomPadding = 1 }; _treeFilter = new TreeModelFilter(new TreeModelAdapter(_treeModel), null) { VisibleFunc = TreeModelVisibilityFunc }; _treeSorter = new TreeModelSort(_treeFilter); _treeSorter.SetSortFunc(0, SortGameTreeRow); _treeSorter.SetSortColumnId(0, SortType.Descending); this.Tree = new TreeView(_treeSorter) { HeadersVisible = true, EnableTreeLines = true }; var nodeIconRenderer = new CellRendererPixbuf { Xalign = 0.0f }; var nodeNameRenderer = new CellRendererText { Xalign = 0.0f }; var column = new TreeViewColumn { Title = "Data Files", Spacing = 4 }; column.PackStart(nodeIconRenderer, false); column.PackStart(nodeNameRenderer, false); column.SetCellDataFunc(nodeIconRenderer, RenderNodeIcon); column.SetCellDataFunc(nodeNameRenderer, RenderNodeName); this.Tree.AppendColumn(column); var sw = new ScrolledWindow { this.Tree }; _treeAlignment.Add(sw); this.Tree.RowActivated += OnRowActivated; this.Tree.ButtonPressEvent += OnButtonPressed; this.Tree.Selection.Changed += OnSelectionChanged; _treeContextMenu = new Menu(); // Save item context button _saveItem = new ImageMenuItem { UseStock = true, Label = Stock.Save, CanFocus = false, TooltipText = "Save the currently selected item to disk.", UseUnderline = true }; _saveItem.Activated += OnSaveItem; _treeContextMenu.Add(_saveItem); // Export item context button _exportItem = new ImageMenuItem("Export") { Image = new Image(Stock.Convert, IconSize.Button), CanFocus = false, TooltipText = "Exports the currently selected item to another format.", }; _exportItem.Activated += OnExportItemRequested; _treeContextMenu.Add(_exportItem); // Open item context button _openItem = new ImageMenuItem { UseStock = true, Label = Stock.Open, CanFocus = false, TooltipText = "Open the currently selected item.", UseUnderline = true }; _openItem.Activated += OnOpenItem; _treeContextMenu.Add(_openItem); // Queue for export context button _queueForExportItem = new ImageMenuItem("Queue for export") { Image = new Image(Stock.Convert, IconSize.Button), CanFocus = false, TooltipText = "Queues the currently selected item for batch export.", }; _queueForExportItem.Activated += OnQueueForExportRequested; _treeContextMenu.Add(_queueForExportItem); // Separator var separator = new SeparatorMenuItem(); _treeContextMenu.Add(separator); // Copy path context button _copyPathItem = new ImageMenuItem("Copy path") { Image = new Image(Stock.Copy, IconSize.Button), CanFocus = false, TooltipText = "Copy the path of the currently selected item.", }; _copyPathItem.Activated += OnCopyPath; _treeContextMenu.Add(_copyPathItem); _treeAlignment.ShowAll(); }
public Tree() { this.serializedTree = new SerializedTree(); }
void OnGUI() { if (attachedWindows.Count >= 2) { for (int i = 0; i < attachedWindows.Count; i += 2) { DrawNodeCurve(windows[attachedWindows[i]], windows[attachedWindows[i + 1]]); } } //Debug.Log ("loaded windows: " + loadedWindowsAttached.Count); //draw the branch when loaded if (loadedWindowsAttached.Count >= 2) { for (int i = 0; i < loadedWindowsAttached.Count; i += 2) { DrawNodeCurve(loadWindows[loadedWindowsAttached[i]], loadWindows[loadedWindowsAttached[i + 1]]); }//end of for loop //loadedWindowsAttached = new List<int> (); } //loadedWindowsAttached = new List<int> (); BeginWindows(); if (GUILayout.Button("Create Node")) { if (!loadTree) { windows.Add(new Rect(10, 10, 200, 200)); } else { loadWindows.Add(new Rect(10, 10, 200, 200)); listTree.Add(new DialogueTree()); loadedDialogues.Add("Add new dialogue"); } dialogues.Add("Add new dialogue here"); } //when adding windows in tree creation mode AddWindows(); //when loading windows from an existing tree for (int i = 0; i < loadWindows.Count; i++) { string rightDialogue = ((listTree[i].getRight() != null) && (DialogueTree.getBranch(listTree[i], listTree[i].getRight()) != null)) ? DialogueTree.getBranch(listTree[i], listTree[i].getLeft()).getData() : ("insert right response"); string leftDialogue = ((listTree[i].getLeft() != null) && (DialogueTree.getBranch(listTree[i], listTree[i].getLeft()) != null)) ? DialogueTree.getBranch(listTree[i], listTree[i].getLeft()).getData() : ("insert left response"); loadedLefts.Add(leftDialogue); loadedRights.Add(rightDialogue); loadWindows[i] = GUI.Window(i, loadWindows[i], LoadTreeWindow, "Window " + i); }//end of for loop saveTreeToObject = (GameObject)EditorGUILayout.ObjectField("Game Object to Save/Load Tree", saveTreeToObject, typeof(GameObject), true); if (GUILayout.Button("Save Tree")) { loadTree = false; SerializedTree sTree = saveTreeToObject.GetComponent <SerializedTree>(); sTree.SaveDialogueTree(dTree); DialogueTree.SaveDialogueBranches(); Debug.Log("Your tree has been saved"); } if (GUILayout.Button("Load Tree")) { //zero here //Debug.Log ("load count: " + loadedWindowsAttached.Count); if (saveTreeToObject != null) { loadTree = true; loadWindows = new List <Rect>(); SerializedTree sTree = saveTreeToObject.GetComponent <SerializedTree>(); savedTrees = sTree.LoadDialogueTree(); //savedTrees[sTree.getID()].traverseTree(); //you don't need this List <DialogueTree.DialogueBranch> branches = DialogueTree.LoadDialogueBranches(); if (SerializedTree.getSavedTrees().ContainsKey(sTree.getID())) { //dTree = sTree.getSavedTree(); listTree = sTree.getTreeInList(savedTrees[sTree.getID()]); tree = listTree; dTree = listTree [0]; Debug.Log("ListTree Count: " + listTree.Count); for (int i = 0; i < listTree.Count; i++) { //create windows loadWindows.Add(new Rect(10, 10, 200, 200)); //add loaded dialogues //string currDialogue = loadedDialogues.Add(listTree[i].getDialogue()); }//end of for loop //dTree = listTree[0]; } else { Debug.Log("Your dialogue tree is null"); } } }//end of load button if (GUILayout.Button("Clear Dialogue Tree")) { ClearTreeButton(); dTree = null; saveTreeToObject.GetComponent <SerializedTree>().SaveDialogueTree(dTree); Debug.Log("saved tree after clear: " + saveTreeToObject.GetComponent <SerializedTree>().getSavedTree()); Debug.Log("Your dialogue tree has been cleared"); } EndWindows(); }//end of OnGUI
private void AddGamePage(string alias, WarcraftVersion version, PackageGroup group, SerializedTree nodeTree) { var page = new GamePage(group, nodeTree, version, alias); page.FileLoadRequested += OnFileLoadRequested; page.SaveRequested += OnSaveRequested; page.ExportItemRequested += OnExportItemRequested; page.EnqueueFileExportRequested += OnEnqueueItemRequested; _gamePages.Add(page); _gameTabNotebook.AppendPage(page.PageWidget, new Label(page.Alias)); _gameTabNotebook.SetTabReorderable(page.PageWidget, true); _gameTabNotebook.ShowAll(); }
/// <summary> /// Attempts to load a game in a specified path, returning a <see cref="PackageGroup"/> object with the /// packages in the path and an <see cref="SerializedTree"/> with a fully qualified node tree of the /// package group. /// If no packages are found, then this method will return null in both fields. /// </summary> /// <param name="gameAlias">The alias of the game at the path.</param> /// <param name="gamePath">The path to load as a game.</param> /// <param name="ct">A cancellation token.</param> /// <param name="progress">An <see cref="IProgress{GameLoadingProgress}"/> object for progress reporting.</param> /// <returns>A tuple with a package group and a node tree for the requested game.</returns> public async Task <(PackageGroup?packageGroup, SerializedTree?nodeTree)> LoadGameAsync ( string gameAlias, string gamePath, CancellationToken ct, IProgress <GameLoadingProgress>?progress = null ) { progress?.Report(new GameLoadingProgress { CompletionPercentage = 0.0f, State = GameLoadingState.SettingUp, Alias = gameAlias }); var packagePaths = Directory.EnumerateFiles ( gamePath, "*", SearchOption.AllDirectories ) .Where(p => p.EndsWith(".mpq", StringComparison.InvariantCultureIgnoreCase)) .OrderBy(p => p) .ToList(); if (packagePaths.Count == 0) { return(null, null); } var packageSetHash = GeneratePathSetHash(packagePaths); var packageTreeFilename = $".{packageSetHash}.tree"; var packageTreeFilePath = Path.Combine(gamePath, packageTreeFilename); var packageGroup = new PackageGroup(packageSetHash); SerializedTree?nodeTree = null; var generateTree = true; if (File.Exists(packageTreeFilePath)) { progress?.Report(new GameLoadingProgress { CompletionPercentage = 0, State = GameLoadingState.LoadingNodeTree, Alias = gameAlias }); try { // Load tree nodeTree = new SerializedTree(File.OpenRead(packageTreeFilePath)); generateTree = false; } catch (FileNotFoundException) { Log.Error("No file for the node tree found at the given location."); } catch (NotSupportedException) { Log.Info("Unsupported node tree version present. Deleting and regenerating."); File.Delete(packageTreeFilePath); } } if (generateTree) { // Internal counters for progress reporting double completedSteps = 0; double totalSteps = packagePaths.Count * 2; // Load packages var packages = new List <(string packageName, IPackage package)>(); foreach (var packagePath in packagePaths) { ct.ThrowIfCancellationRequested(); progress?.Report(new GameLoadingProgress { CompletionPercentage = completedSteps / totalSteps, State = GameLoadingState.LoadingPackages, Alias = gameAlias }); try { var package = await PackageInteractionHandler.LoadAsync(packagePath); packages.Add((Path.GetFileNameWithoutExtension(packagePath), package)); } catch (FileLoadException fex) { Log.Warn($"Failed to load archive {Path.GetFileNameWithoutExtension(packagePath)}: {fex.Message}"); } ++completedSteps; } // Load dictionary if neccesary if (_dictionary == null) { progress?.Report(new GameLoadingProgress { CompletionPercentage = completedSteps / totalSteps, State = GameLoadingState.LoadingDictionary, Alias = gameAlias }); _dictionary = await LoadDictionaryAsync(ct); } // Generate node tree var builder = new TreeBuilder(); foreach (var packageInfo in packages) { ct.ThrowIfCancellationRequested(); progress?.Report(new GameLoadingProgress { CompletionPercentage = completedSteps / totalSteps, State = GameLoadingState.BuildingNodeTree, Alias = gameAlias }); var steps = completedSteps; var createNodesProgress = new Progress <PackageNodesCreationProgress> ( p => { progress?.Report ( new GameLoadingProgress { CompletionPercentage = steps / totalSteps, State = GameLoadingState.BuildingNodeTree, Alias = gameAlias, CurrentPackage = packageInfo.packageName, NodesCreationProgress = p } ); } ); await Task.Run(() => builder.AddPackage(packageInfo.packageName, packageInfo.package, createNodesProgress, ct), ct); packageGroup.AddPackage((PackageInteractionHandler)packageInfo.package); ++completedSteps; } // Build node tree var tree = builder.GetTree(); var optimizeTreeProgress = new Progress <TreeOptimizationProgress> ( p => { progress?.Report ( new GameLoadingProgress { CompletionPercentage = completedSteps / totalSteps, State = GameLoadingState.BuildingNodeTree, Alias = gameAlias, OptimizationProgress = p } ); } ); var optimizer = new TreeOptimizer(_dictionary); var treeClosureCopy = tree; tree = await Task.Run(() => optimizer.OptimizeTree(treeClosureCopy, optimizeTreeProgress, ct), ct); using (var fs = File.OpenWrite(packageTreeFilePath)) { using (var serializer = new TreeSerializer(fs)) { await serializer.SerializeAsync(tree, ct); } } nodeTree = new SerializedTree(File.OpenRead(packageTreeFilePath)); } else { progress?.Report(new GameLoadingProgress { CompletionPercentage = 1, State = GameLoadingState.LoadingPackages, Alias = gameAlias }); // Load packages packageGroup = await PackageGroup.LoadAsync(gameAlias, packageSetHash, gamePath, ct, progress); } progress?.Report(new GameLoadingProgress { CompletionPercentage = 1, State = GameLoadingState.Loading, Alias = gameAlias }); return(packageGroup, nodeTree); }
/// <summary> /// Initializes a new instance of the <see cref="FileTreeModel"/> class. /// </summary> /// <param name="nodeTree">The precomputed node tree to wrap around.</param> public FileTreeModel(SerializedTree nodeTree) { _tree = nodeTree; _stamp = new Random().Next(); }
/// <summary> /// Initializes a new instance of the <see cref="FileTreeModel"/> class. /// </summary> /// <param name="nodeTree">The precomputed node tree to wrap around.</param> public FileTreeModel(SerializedTree nodeTree) { this.Tree = nodeTree; this.Stamp = new Random().Next(); }