/// <summary> /// Instantiates a new SteinerTabViewModel. /// </summary> /// <param name="tree">The (not null) SkillTree instance to operate on.</param> /// <param name="dialogCoordinator">The <see cref="IDialogCoordinator"/> used to display dialogs.</param> /// <param name="dialogContext">The context used for <paramref name="dialogCoordinator"/>.</param> /// <param name="runCallback">The action that is called when RunCommand is executed.</param> public SteinerTabViewModel(SkillTree tree, IDialogCoordinator dialogCoordinator, object dialogContext, Action<GeneratorTabViewModel> runCallback) : base(tree, dialogCoordinator, dialogContext, 1, runCallback) { DisplayName = L10n.Message("Tagged Nodes"); SubSettings = new[] {ExcludeCrossed}; }
public static void Initalize(TestContext testContext) { AppData.SetApplicationData(Environment.CurrentDirectory); if (ItemDB.IsEmpty()) ItemDB.Load("Items.xml", true); Tree = SkillTree.CreateSkillTree(() => { Debug.WriteLine("Download started"); }, (double dummy1, double dummy2) => { }, () => { Debug.WriteLine("Download finished"); }); }
public async Task<IEnumerable<ushort>> ShowControllerDialogAsync(object context, ISolver solver, string generatorName, SkillTree tree) { var vm = new ControllerViewModel(solver, generatorName, tree, this); var view = new ControllerWindow(); Task<IEnumerable<ushort>> task = null; await ShowDialogAsync(context, vm, view, () => task = vm.RunSolverAsync()); return await task; }
public TreeGeneratorInteraction(ISettingsDialogCoordinator dialogCoordinator, IPersistentData persistentData, SkillTree skillTree) { _persistentData = persistentData; _dialogCoordinator = dialogCoordinator; SkillTree = skillTree; OpenTreeGeneratorCommand = new AsyncRelayCommand(OpenTreeGenerator); RunTaggedNodesCommand = new AsyncRelayCommand(RunTaggedNodes); RunAdvancedCommand = new AsyncRelayCommand(RunAdvanced); }
public void OpenOrDownloadImages(SkillTree.UpdateLoadingWindow update = null) { //Application foreach (string image in Images.Keys.ToArray()) { if (!File.Exists(SkillTree.AssetsFolderPath + image)) { var _WebClient = new WebClient(); _WebClient.DownloadFile(urlpath + image, SkillTree.AssetsFolderPath + image); } Images[image] = ImageHelper.OnLoadBitmapImage(new Uri(SkillTree.AssetsFolderPath + image, UriKind.Absolute)); } }
public OptimizerControllerWindow(SkillTree tree, HashSet<ushort> targetNodes) { InitializeComponent(); this.tree = tree; steinerSolver = new SteinerSolver(tree); this.targetNodes = targetNodes; initializationWorker.DoWork += initializationWorker_DoWork; initializationWorker.RunWorkerCompleted += initializationWorker_RunWorkerCompleted; solutionWorker.DoWork += solutionWorker_DoWork; solutionWorker.ProgressChanged += solutionWorker_ProgressChanged; solutionWorker.RunWorkerCompleted += solutionWorker_RunWorkerCompleted; solutionWorker.WorkerReportsProgress = true; solutionWorker.WorkerSupportsCancellation = true; }
/// <summary> /// Constructs a new SettingsViewModel that operates on the given skill tree. /// </summary> /// <param name="tree">The skill tree to operate on. (not null)</param> /// <param name="dialogCoordinator"></param> public SettingsViewModel(SkillTree tree, ISettingsDialogCoordinator dialogCoordinator) { Tree = tree; _dialogCoordinator = dialogCoordinator; SelectedTabIndex = new LeafSetting<int>(nameof(SelectedTabIndex), 0); Action<GeneratorTabViewModel> runCallback = async g => await RunAsync(g); Tabs = new ObservableCollection<GeneratorTabViewModel> { new SteinerTabViewModel(Tree, _dialogCoordinator, this, runCallback), new AdvancedTabViewModel(Tree, _dialogCoordinator, this, runCallback), new AutomatedTabViewModel(Tree, _dialogCoordinator, this, runCallback) }; SubSettings = new ISetting[] {SelectedTabIndex}.Union(Tabs).ToArray(); }
public static SkillTree CreateSkillTree(StartLoadingWindow start = null, UpdateLoadingWindow update = null, CloseLoadingWindow finish = null) { AssetsFolderPath = AppData.GetFolder(Path.Combine("Data", "Assets"), true); DataFolderPath = AppData.GetFolder("Data", true); string skillTreeFile = DataFolderPath + "Skilltree.txt"; string skilltreeobj = ""; if (File.Exists(skillTreeFile)) { skilltreeobj = File.ReadAllText(skillTreeFile); } bool displayProgress = false; if (skilltreeobj == "") { displayProgress = (start != null && update != null && finish != null); if (displayProgress) { start(L10n.Message("Downloading Skill tree assets")); } string uriString = SkillTree.TreeAddress; var req = (HttpWebRequest)WebRequest.Create(uriString); var resp = (HttpWebResponse)req.GetResponse(); string code = new StreamReader(resp.GetResponseStream()).ReadToEnd(); var regex = new Regex("var passiveSkillTreeData.*"); skilltreeobj = regex.Match(code).Value.Replace("\\/", "/"); skilltreeobj = skilltreeobj.Substring(27, skilltreeobj.Length - 27 - 1) + ""; File.WriteAllText(skillTreeFile, skilltreeobj); } if (displayProgress) { update(25, 100); } var skillTree = new SkillTree(skilltreeobj, displayProgress, update); if (displayProgress) { finish(); } return(skillTree); }
/// <summary> /// Instantiates a new AdvancedTabViewModel. /// </summary> /// <param name="tree">The (not null) SkillTree instance to operate on.</param> /// <param name="dialogCoordinator">The <see cref="IDialogCoordinator"/> used to display dialogs.</param> /// <param name="dialogContext">The context used for <paramref name="dialogCoordinator"/>.</param> /// <param name="runCallback">The action that is called when RunCommand is executed.</param> public AdvancedTabViewModel(SkillTree tree, IDialogCoordinator dialogCoordinator, object dialogContext, Action<GeneratorTabViewModel> runCallback) : base(tree, dialogCoordinator, dialogContext, 3, runCallback) { AdditionalPoints = new LeafSetting<int>(nameof(AdditionalPoints), 21, () => TotalPoints = Tree.Level - 1 + AdditionalPoints.Value); TotalPoints = Tree.Level - 1 + AdditionalPoints.Value; TreePlusItemsMode = new LeafSetting<bool>(nameof(TreePlusItemsMode), false); WeaponClass = new LeafSetting<WeaponClass>(nameof(WeaponClass), Model.PseudoAttributes.WeaponClass.Unarmed, () => WeaponClassIsTwoHanded = WeaponClass.Value.IsTwoHanded()); OffHand = new LeafSetting<OffHand>(nameof(OffHand), Model.PseudoAttributes.OffHand.Shield); Tags = new LeafSetting<Tags>(nameof(Tags), Model.PseudoAttributes.Tags.None); tree.PropertyChanged += (sender, args) => { if (args.PropertyName == nameof(SkillTree.Level)) { TotalPoints = Tree.Level - 1 + AdditionalPoints.Value; } }; _attributes = CreatePossibleAttributes().ToList(); AttributesView = new ListCollectionView(_attributes) { Filter = item => !_addedAttributes.Contains(item), CustomSort = Comparer<string>.Create((s1, s2) => { // Sort by group as in AttrGroupOrder first and then by name. var groupCompare = AttrGroupOrder[AttrToGroupConverter.Convert(s1)].CompareTo( AttrGroupOrder[AttrToGroupConverter.Convert(s2)]); return groupCompare != 0 ? groupCompare : string.CompareOrdinal(s1, s2); }) }; AttributesView.GroupDescriptions.Add(new PropertyGroupDescription(".", AttrToGroupConverter)); AttributesView.MoveCurrentToFirst(); AttributeConstraints = new ObservableCollection<AttributeConstraint>(); NewAttributeConstraint = new AttributeConstraint(AttributesView.CurrentItem as string); PseudoAttributesView = new ListCollectionView(_pseudoAttributes) { Filter = item => !_addedPseudoAttributes.Contains((PseudoAttribute) item) }; PseudoAttributesView.SortDescriptions.Add(new SortDescription("Group", ListSortDirection.Ascending)); PseudoAttributesView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending)); PseudoAttributesView.GroupDescriptions.Add(new PropertyGroupDescription("Group")); PseudoAttributeConstraints = new ObservableCollection<PseudoAttributeConstraint>(); ReloadPseudoAttributes(); DisplayName = L10n.Message("Advanced"); SubSettings = new ISetting[] { AdditionalPoints, Iterations, IncludeChecked, ExcludeCrossed, TreePlusItemsMode, WeaponClass, OffHand, Tags, new ConstraintsSetting(this) }; }
/// <summary> /// Loads from the unofficial online tool /// </summary> public static async Task LoadBuildFromPoezone(IDialogCoordinator dialogCoordinator, SkillTree tree, string buildUrl) { if (!buildUrl.Contains('#')) { throw new FormatException(); } const string dataUrl = "http://poezone.ru/skilltree/data.js"; const string buildPostUrl = "http://poezone.ru/skilltree/"; string build = buildUrl.Substring(buildUrl.LastIndexOf('#') + 1); string dataFile, buildFile; { var req = (HttpWebRequest)WebRequest.Create(dataUrl); req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30"; WebResponse resp = req.GetResponse(); dataFile = new StreamReader(resp.GetResponseStream()).ReadToEnd(); } { string postData = "build=" + build; byte[] postBytes = Encoding.ASCII.GetBytes(postData); var req = (HttpWebRequest)WebRequest.Create(buildPostUrl); req.Method = "POST"; req.ContentLength = postBytes.Length; req.ContentType = "application/x-www-form-urlencoded"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30"; req.Accept = "application/json, text/javascript, */*; q=0.01"; req.Host = "poezone.ru"; req.Referer = "http://poezone.ru/skilltree/"; req.AutomaticDecompression = DecompressionMethods.GZip; req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3"); req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch"); req.Headers.Add("Accept-Language", "en-US,en;q=0.8"); req.Headers.Add("Origin", "http://poezone.ru"); req.Headers.Add("X-Requested-With", "XMLHttpRequest"); req.Expect = ""; req.Credentials = CredentialCache.DefaultCredentials; Stream dataStream = req.GetRequestStream(); dataStream.Write(postBytes, 0, postBytes.Length); dataStream.Close(); WebResponse resp = req.GetResponse(); buildFile = new StreamReader(resp.GetResponseStream()).ReadToEnd(); } if (!buildFile.Contains("[")) { await dialogCoordinator.ShowErrorAsync(tree, string.Format( L10n.Message("An error occured while attempting to load Skill tree from {0} location."), "poezone.ru")); return; } // position decompose var positions = new List <Vector2D?>(); string[] lines = dataFile.Split('\n'); foreach (string line in lines) { if (line.StartsWith("skillpos=")) { string posString = line.Substring(line.IndexOf('[') + 1, line.LastIndexOf(']') - line.IndexOf('[') - 1); var sb = new StringBuilder(); bool inBracket = false; foreach (char c in posString) { if (!inBracket && c == ',') { positions.Add(sb.Length == 0 ? null : new Vector2D?(new Vector2D( int.Parse(sb.ToString().Split(',')[0]), int.Parse(sb.ToString().Split(',')[1]) ))); sb.Clear(); } else { if (c == '[') { inBracket = true; } else if (c == ']') { inBracket = false; } else { sb.Append(c); } } } positions.Add(sb.Length == 0 ? null : new Vector2D?(new Vector2D( int.Parse(sb.ToString().Split(',')[0]), int.Parse(sb.ToString().Split(',')[1]) ))); } } // min max double minx = float.MaxValue, miny = float.MaxValue, maxx = float.MinValue, maxy = float.MinValue; foreach (var posn in positions) { if (!posn.HasValue) { continue; } Vector2D pos = posn.Value; minx = Math.Min(pos.X, minx); miny = Math.Min(pos.Y, miny); maxx = Math.Max(pos.X, maxx); maxy = Math.Max(pos.Y, maxy); } double nminx = float.MaxValue, nminy = float.MaxValue, nmaxx = float.MinValue, nmaxy = float.MinValue; foreach (SkillNode node in SkillTree.Skillnodes.Values) { Vector2D pos = node.Position; nminx = Math.Min(pos.X, nminx); nminy = Math.Min(pos.Y, nminy); nmaxx = Math.Max(pos.X, nmaxx); nmaxy = Math.Max(pos.Y, nmaxy); } //respose string[] buildResp = buildFile.Replace("[", "").Replace("]", "").Split(','); int character = int.Parse(buildResp[0]); var skilled = new List <int>(); tree.Chartype = character; tree.SkilledNodes.Clear(); SkillNode startnode = SkillTree.Skillnodes.First(nd => nd.Value.Name == SkillTree.CharName[tree.Chartype].ToUpper()).Value; tree.AllocateSkillNode(startnode); for (int i = 1; i < buildResp.Length; ++i) { if (!positions[int.Parse(buildResp[i])].HasValue) { Debugger.Break(); } Vector2D poezonePos = (positions[int.Parse(buildResp[i])].Value - new Vector2D(minx, miny)) * new Vector2D(1 / (maxx - minx), 1 / (maxy - miny)); double minDis = 2; var minNode = new KeyValuePair <ushort, SkillNode>(); foreach (var node in SkillTree.Skillnodes) { Vector2D nodePos = (node.Value.Position - new Vector2D(nminx, nminy)) * new Vector2D(1 / (nmaxx - nminx), 1 / (nmaxy - nminy)); double dis = (nodePos - poezonePos).Length; if (dis < minDis) { minDis = dis; minNode = node; } } tree.AllocateSkillNode(minNode.Value); } }
private static int CalculateAdditionalPointsNeeded(SkillTree tree) { if (tree.Level != SkillTree.UndefinedLevel && tree.SkilledNodes.Count > 1 && tree.SkilledNodes.Count - tree.Level >= 0) { return tree.SkilledNodes.Count - tree.Level; } return AdditionalPointsDefaultValue; }
public AutomatedTabViewModel(SkillTree tree) : base(tree) { DisplayName = L10n.Message("Automated"); }
public static SkillTree CreateSkillTree(StartLoadingWindow start = null, UpdateLoadingWindow update = null, CloseLoadingWindow finish = null) { AssetsFolderPath = AppData.GetFolder(Path.Combine("Data", "Assets"), true); DataFolderPath = AppData.GetFolder("Data", true); string skillTreeFile = DataFolderPath + "Skilltree.txt"; string skilltreeobj = ""; if (File.Exists(skillTreeFile)) { skilltreeobj = File.ReadAllText(skillTreeFile); } bool displayProgress = false; if (skilltreeobj == "") { displayProgress = (start != null && update != null && finish != null); if (displayProgress) start(L10n.Message("Downloading Skill tree assets")); string uriString = SkillTree.TreeAddress; var req = (HttpWebRequest)WebRequest.Create(uriString); var resp = (HttpWebResponse)req.GetResponse(); string code = new StreamReader(resp.GetResponseStream()).ReadToEnd(); var regex = new Regex("var passiveSkillTreeData.*"); skilltreeobj = regex.Match(code).Value.Replace("\\/", "/"); skilltreeobj = skilltreeobj.Substring(27, skilltreeobj.Length - 27 - 1) + ""; File.WriteAllText(skillTreeFile, skilltreeobj); } if (displayProgress) update(25, 100); var skillTree = new SkillTree(skilltreeobj, displayProgress, update); if (displayProgress) finish(); return skillTree; }
/// <summary> /// Constructs a new SettingsViewModel that operates on the given skill tree. /// </summary> /// <param name="tree">The skill tree to operate on. (not null)</param> /// <param name="generator">Optional <see cref="GeneratorTabViewModel"/> initialize /// <see cref="Tabs"/> with. If non is provided, <see cref="AdvancedTabViewModel"/>, /// <see cref="AutomatedTabViewModel"/> and <see cref="SteinerTabViewModel"/> will be /// added to <see cref="Tabs"/>.</param> public SettingsViewModel(SkillTree tree, GeneratorTabViewModel generator = null) { if (tree == null) throw new ArgumentNullException("tree"); DisplayName = L10n.Message("Skill tree Generator"); _tree = tree; AdditionalPoints = CalculateAdditionalPointsNeeded(tree); tree.PropertyChanged += (sender, args) => { if (args.PropertyName == "Level") { TotalPoints = _tree.Level - 1 + _additionalPoints; } }; if (generator == null) { CreateTabs(); } else { Tabs = new ObservableCollection<GeneratorTabViewModel> { generator }; } }
/// <summary> /// Instantiates a new GeneratorTabViewModel. /// </summary> /// <param name="tree">The (not null) SkillTree instance to operate on.</param> protected GeneratorTabViewModel(SkillTree tree) { if (tree == null) throw new ArgumentNullException("tree"); Tree = tree; }
/// <summary> /// Returns a task that finishes with a SkillTree object once it has been initialized. /// </summary> /// <param name="persistentData"></param> /// <param name="dialogCoordinator">Can be null if the resulting tree is not used.</param> /// <param name="controller">Null if no initialization progress should be displayed.</param> /// <param name="assetLoader">Can optionally be provided if the caller wants to backup assets.</param> /// <returns></returns> public static async Task<SkillTree> CreateAsync(IPersistentData persistentData, IDialogCoordinator dialogCoordinator, ProgressDialogController controller = null, AssetLoader assetLoader = null) { controller?.SetProgress(0); var dataFolderPath = AppData.GetFolder("Data", true); _assetsFolderPath = dataFolderPath + "Assets/"; if (assetLoader == null) assetLoader = new AssetLoader(new HttpClient(), dataFolderPath, false); var skillTreeTask = LoadTreeFileAsync(dataFolderPath + "Skilltree.txt", () => assetLoader.DownloadSkillTreeToFileAsync()); var optsTask = LoadTreeFileAsync(dataFolderPath + "Opts.txt", () => assetLoader.DownloadOptsToFileAsync()); await Task.WhenAny(skillTreeTask, optsTask); controller?.SetProgress(0.1); var skillTreeObj = await skillTreeTask; var optsObj = await optsTask; controller?.SetProgress(0.25); var tree = new SkillTree(persistentData, dialogCoordinator); await tree.InitializeAsync(skillTreeObj, optsObj, controller, assetLoader); return tree; }
private void Menu_RedownloadTreeAssets(object sender, RoutedEventArgs e) { string sMessageBoxText = L10n.Message("The existing Skill tree assets will be deleted and new assets will be downloaded.") + "\n\n" + L10n.Message("Do you want to continue?"); var rsltMessageBox = Popup.Ask(sMessageBoxText, MessageBoxImage.Warning); switch (rsltMessageBox) { case MessageBoxResult.Yes: string appDataPath = AppData.GetFolder(true); try { if (Directory.Exists(appDataPath + "Data")) { if (Directory.Exists(appDataPath + "DataBackup")) Directory.Delete(appDataPath + "DataBackup", true); Directory.Move(appDataPath + "Data", appDataPath + "DataBackup"); } Tree = SkillTree.CreateSkillTree(StartLoadingWindow, UpdateLoadingWindow, CloseLoadingWindow); recSkillTree.Fill = new VisualBrush(Tree.SkillTreeVisual); SkillTree.ClearAssets();//enable recaching of assets SkillTree.CreateSkillTree();//create new skilltree to reinitialize cache btnLoadBuild_Click(this, new RoutedEventArgs()); _justLoaded = false; if (Directory.Exists(appDataPath + "DataBackup")) Directory.Delete(appDataPath + "DataBackup", true); } catch (Exception ex) { if (Directory.Exists(appDataPath + "Data")) Directory.Delete(appDataPath + "Data", true); try { CloseLoadingWindow(); } catch (Exception) { //Nothing } Directory.Move(appDataPath + "DataBackup", appDataPath + "Data"); Popup.Error(L10n.Message("An error occurred while downloading assets."), ex.Message); } break; case MessageBoxResult.No: //Do nothing break; } }
public AutomatedTabViewModel(SkillTree tree, IDialogCoordinator dialogCoordinator, object dialogContext, Action<GeneratorTabViewModel> runCallback) : base(tree, dialogCoordinator, dialogContext, 1, runCallback) { DisplayName = L10n.Message("Automated"); }
/// <summary> /// Instantiates a new SteinerTabViewModel. /// </summary> /// <param name="tree">The (not null) SkillTree instance to operate on.</param> public SteinerTabViewModel(SkillTree tree) : base(tree) { DisplayName = L10n.Message("Tagged Nodes"); }
/// <summary> /// Instantiates a new ControllerViewModel. /// </summary> /// <param name="solver">The (not null) solver this object should run.</param> /// <param name="generatorName">The name suffix shown as DisplayName as 'Skill tree generator - {generatorName}'</param> /// <param name="tree">SkillTree to operate on (not null)</param> /// <param name="dialogCoordinator"></param> public ControllerViewModel(ISolver solver, string generatorName, SkillTree tree, IDialogCoordinator dialogCoordinator) { if (solver == null) throw new ArgumentNullException("solver"); if (tree == null) throw new ArgumentNullException("tree"); _solver = solver; DisplayName = L10n.Message("Skill tree generator") + " - " + generatorName; _tree = tree; _dialogCoordinator = dialogCoordinator; if (_solver.Iterations > 1) IterationText = IterationPrefix + "1/" + _solver.Iterations; _progress = new Progress<Tuple<int, int, IEnumerable<ushort>>>(tuple => ReportProgress(tuple.Item1, tuple.Item2, tuple.Item3)); _reportStopwatch.Start(); RequestsClose += _ => CancelClose(); }
/// <summary> /// Instantiates a new AdvancedTabViewModel. /// </summary> /// <param name="tree">The (not null) SkillTree instance to operate on.</param> public AdvancedTabViewModel(SkillTree tree) : base(tree) { _attributes = CreatePossibleAttributes().ToList(); AttributesView = new ListCollectionView(_attributes) { Filter = item => !_addedAttributes.Contains(item), CustomSort = Comparer<string>.Create((s1, s2) => { // Sort by group as in AttrGroupOrder first and then by name. var groupCompare = AttrGroupOrder[AttrToGroupConverter.Convert(s1)].CompareTo( AttrGroupOrder[AttrToGroupConverter.Convert(s2)]); return groupCompare != 0 ? groupCompare : string.CompareOrdinal(s1, s2); }) }; AttributesView.GroupDescriptions.Add(new PropertyGroupDescription(".", AttrToGroupConverter)); AttributesView.MoveCurrentToFirst(); AttributeConstraints = new ObservableCollection<AttributeConstraint>(); NewAttributeConstraint = new AttributeConstraint(AttributesView.CurrentItem as string); PseudoAttributesView = new ListCollectionView(_pseudoAttributes) { Filter = item => !_addedPseudoAttributes.Contains((PseudoAttribute) item) }; PseudoAttributesView.SortDescriptions.Add(new SortDescription("Group", ListSortDirection.Ascending)); PseudoAttributesView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending)); PseudoAttributesView.GroupDescriptions.Add(new PropertyGroupDescription("Group")); PseudoAttributeConstraints = new ObservableCollection<PseudoAttributeConstraint>(); ReloadPseudoAttributes(); DisplayName = L10n.Message("Advanced"); }
/// <summary> /// Instantiates a new ControllerViewModel. /// </summary> /// <param name="solver">The (not null) solver this object should run.</param> /// <param name="generatorName">The name suffix shown as DisplayName as 'Skill tree generator - {generatorName}'</param> /// <param name="tree">SkillTree to operate on (not null)</param> public ControllerViewModel(ISolver solver, string generatorName, SkillTree tree) { if (solver == null) throw new ArgumentNullException("solver"); if (tree == null) throw new ArgumentNullException("tree"); _solver = solver; DisplayName = L10n.Message("Skill tree generator") + " - " + generatorName; _tree = tree; _progress = new Progress<Tuple<int, IEnumerable<ushort>>>(tuple => ReportProgress(tuple.Item1, tuple.Item2)); _reportStopwatch.Start(); RequestClose += (sender, args) => CancelClose(); }
private void Window_Loaded(object sender, RoutedEventArgs e) { ItemDB.Load("Items.xml"); ItemDB.Merge("ItemsLocal.xml"); ItemDB.Index(); _attibuteCollection = new ListCollectionView(_attiblist); listBox1.ItemsSource = _attibuteCollection; _attibuteCollection.GroupDescriptions.Add(new PropertyGroupDescription("Text") { Converter = new GroupStringConverter() }); _allAttributeCollection = new ListCollectionView(_allAttributesList); _allAttributeCollection.GroupDescriptions.Add(new PropertyGroupDescription("Text") { Converter = new GroupStringConverter() }); lbAllAttr.ItemsSource = _allAttributeCollection; _defenceCollection = new ListCollectionView(_defenceList); _defenceCollection.GroupDescriptions.Add(new PropertyGroupDescription("Group")); listBoxDefence.ItemsSource = _defenceCollection; _offenceCollection = new ListCollectionView(_offenceList); _offenceCollection.GroupDescriptions.Add(new PropertyGroupDescription("Group")); listBoxOffence.ItemsSource = _offenceCollection; if (_persistentData.StashBookmarks != null) Stash.Bookmarks = new System.Collections.ObjectModel.ObservableCollection<StashBookmark>(_persistentData.StashBookmarks); // Set theme & accent. SetTheme(_persistentData.Options.Theme); SetAccent(_persistentData.Options.Accent); Tree = SkillTree.CreateSkillTree(StartLoadingWindow, UpdateLoadingWindow, CloseLoadingWindow); Tree.MainWindow = this; recSkillTree.Width = SkillTree.TRect.Width / SkillTree.TRect.Height * recSkillTree.Height; recSkillTree.UpdateLayout(); recSkillTree.Fill = new VisualBrush(Tree.SkillTreeVisual); Tree.Chartype = SkillTree.CharName.IndexOf(((string)((ComboBoxItem)cbCharType.SelectedItem).Name).ToUpper()); Tree.UpdateAvailNodes(); UpdateUI(); _multransform = SkillTree.TRect.Size / new Vector2D(recSkillTree.RenderSize.Width, recSkillTree.RenderSize.Height); _addtransform = SkillTree.TRect.TopLeft; // loading last build if (_persistentData.CurrentBuild != null) SetCurrentBuild(_persistentData.CurrentBuild); btnLoadBuild_Click(this, new RoutedEventArgs()); _justLoaded = false; // loading saved build lvSavedBuilds.Items.Clear(); foreach (var build in _persistentData.Builds) { lvSavedBuilds.Items.Add(build); } ImportLegacySavedBuilds(); }
// Initializes structures. public static void Initialize(SkillTree skillTree, ItemAttributes itemAttrs) { Items = itemAttrs.Equip.ToList(); MainHand = new Weapon(WeaponHand.Main, Items.Find(i => i.Class == ItemClass.MainHand)); OffHand = new Weapon(WeaponHand.Off, Items.Find(i => i.Class == ItemClass.OffHand)); // If main hand weapon has Counts as Dual Wielding modifier, then clone weapon to off hand. // @see http://pathofexile.gamepedia.com/Wings_of_Entropy if (MainHand.Attributes.ContainsKey("Counts as Dual Wielding")) OffHand = MainHand.Clone(WeaponHand.Off); IsDualWielding = MainHand.IsWeapon() && OffHand.IsWeapon(); if (IsDualWielding) { // Set dual wielded bit on weapons. MainHand.Hand |= WeaponHand.DualWielded; OffHand.Hand |= WeaponHand.DualWielded; } IsWieldingShield = MainHand.Is(WeaponType.Shield) || OffHand.Is(WeaponType.Shield); IsWieldingStaff = MainHand.Is(WeaponType.Staff); Level = skillTree.Level; if (Level < 1) Level = 1; else if (Level > 100) Level = 100; Global = new AttributeSet(); Tree = new AttributeSet(skillTree.SelectedAttributesWithoutImplicit); Global.Add(Tree); // Keystones. Acrobatics = Tree.ContainsKey("#% Chance to Dodge Attacks. #% less Armour and Energy Shield, #% less Chance to Block Spells and Attacks"); AvatarOfFire = Tree.ContainsKey("Deal no Non-Fire Damage"); BloodMagic = Tree.ContainsKey("Removes all mana. Spend Life instead of Mana for Skills"); ChaosInoculation = Tree.ContainsKey("Maximum Life becomes #, Immune to Chaos Damage"); IronGrip = Tree.ContainsKey("The increase to Physical Damage from Strength applies to Projectile Attacks as well as Melee Attacks"); IronReflexes = Tree.ContainsKey("Converts all Evasion Rating to Armour. Dexterity provides no bonus to Evasion Rating"); NecromanticAegis = Tree.ContainsKey("All bonuses from an equipped Shield apply to your Minions instead of you"); ResoluteTechnique = Tree.ContainsKey("Never deal Critical Strikes"); VaalPact = Tree.ContainsKey("Life Leech applies instantly at #% effectiveness. Life Regeneration has no effect."); ZealotsOath = Tree.ContainsKey("Life Regeneration applies to Energy Shield instead of Life"); Equipment = new AttributeSet(); foreach (ItemAttributes.Attribute attr in itemAttrs.NonLocalMods) Equipment.Add(attr.TextAttribute, new List<float>(attr.Value)); if (NecromanticAegis && OffHand.IsShield()) { // Remove all bonuses of shield from equipment set. // @see http://pathofexile.gamepedia.com/Necromantic_Aegis foreach (var attr in OffHand.Attributes) Equipment.Remove(attr); // Remove all bonuses from shield itself. OffHand.Attributes.Clear(); } Global.Add(Equipment); CoreAttributes(); Implicit = new AttributeSet(SkillTree.ImplicitAttributes(Global, Level)); Global.Add(Implicit); // Innate dual wielding bonuses. // @see http://pathofexile.gamepedia.com/Dual_wielding if (IsDualWielding) { Global["#% more Attack Speed"] = new List<float>() { 10 }; Global["#% more Physical Damage with Weapons"] = new List<float>() { 20 }; } }
public static void Initalize(TestContext testContext) { AppData.SetApplicationData(Environment.CurrentDirectory); Tree = SkillTree.CreateSkillTree((string dummy) => { Debug.WriteLine("Download started"); }, (double dummy1, double dummy2) => { }, () => { Debug.WriteLine("Download finished"); }); }
/// <summary> /// Loads from the unofficial online tool /// </summary> public static void LoadBuildFromPoezone(SkillTree tree, string buildUrl) { if (!buildUrl.Contains('#')) throw new FormatException(); const string dataUrl = "http://poezone.ru/skilltree/data.js"; const string buildPostUrl = "http://poezone.ru/skilltree/"; string build = buildUrl.Substring(buildUrl.LastIndexOf('#') + 1); string dataFile, buildFile; { var req = (HttpWebRequest) WebRequest.Create(dataUrl); req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30"; WebResponse resp = req.GetResponse(); dataFile = new StreamReader(resp.GetResponseStream()).ReadToEnd(); } { string postData = "build=" + build; byte[] postBytes = Encoding.ASCII.GetBytes(postData); var req = (HttpWebRequest) WebRequest.Create(buildPostUrl); req.Method = "POST"; req.ContentLength = postBytes.Length; req.ContentType = "application/x-www-form-urlencoded"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30"; req.Accept = "application/json, text/javascript, */*; q=0.01"; req.Host = "poezone.ru"; req.Referer = "http://poezone.ru/skilltree/"; req.AutomaticDecompression = DecompressionMethods.GZip; //req.Headers.Add( "Accept", "application/json, text/javascript" ); req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3"); req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch"); req.Headers.Add("Accept-Language", "en-US,en;q=0.8"); //req.Headers.Add( "Connection", "keep-alive" ); //req.Headers.Add( "Host", "poezone.ru" ); req.Headers.Add("Origin", "http://poezone.ru"); //req.Headers.Add( "Referer", "http://poezone.ru/skilltree/" ); //req.Headers.Add( "User-Agent", ); req.Headers.Add("X-Requested-With", "XMLHttpRequest"); req.Expect = ""; req.Credentials = CredentialCache.DefaultCredentials; Stream dataStream = req.GetRequestStream(); dataStream.Write(postBytes, 0, postBytes.Length); dataStream.Close(); WebResponse resp = req.GetResponse(); string status = (resp as HttpWebResponse).StatusDescription; buildFile = new StreamReader(resp.GetResponseStream()).ReadToEnd(); } if (!buildFile.Contains("[")) { Popup.Error(string.Format(L10n.Message("An error occured while attempting to load Skill tree from {0} location."), "poezone.ru")); return; } // position decompose var positions = new List<Vector2D?>(); string[] lines = dataFile.Split('\n'); foreach (string line in lines) if (line.StartsWith("skillpos=")) { string posString = line.Substring(line.IndexOf('[') + 1, line.LastIndexOf(']') - line.IndexOf('[') - 1); var sb = new StringBuilder(); bool inBracket = false; foreach (char c in posString) { if (!inBracket && c == ',') { positions.Add(sb.Length == 0 ? null : new Vector2D?(new Vector2D( int.Parse(sb.ToString().Split(',')[0]), int.Parse(sb.ToString().Split(',')[1]) ))); sb.Clear(); } else { if (c == '[') inBracket = true; else if (c == ']') inBracket = false; else sb.Append(c); } } positions.Add(sb.Length == 0 ? null : new Vector2D?(new Vector2D( int.Parse(sb.ToString().Split(',')[0]), int.Parse(sb.ToString().Split(',')[1]) ))); } // min max double minx = float.MaxValue, miny = float.MaxValue, maxx = float.MinValue, maxy = float.MinValue; foreach (var posn in positions) { if (!posn.HasValue) continue; Vector2D pos = posn.Value; minx = Math.Min(pos.X, minx); miny = Math.Min(pos.Y, miny); maxx = Math.Max(pos.X, maxx); maxy = Math.Max(pos.Y, maxy); } double nminx = float.MaxValue, nminy = float.MaxValue, nmaxx = float.MinValue, nmaxy = float.MinValue; foreach (SkillNode node in SkillTree.Skillnodes.Values) { Vector2D pos = node.Position; nminx = Math.Min(pos.X, nminx); nminy = Math.Min(pos.Y, nminy); nmaxx = Math.Max(pos.X, nmaxx); nmaxy = Math.Max(pos.Y, nmaxy); } //respose string[] buildResp = buildFile.Replace("[", "").Replace("]", "").Split(','); int character = int.Parse(buildResp[0]); var skilled = new List<int>(); tree.Chartype = character; tree.SkilledNodes.Clear(); SkillNode startnode = SkillTree.Skillnodes.First(nd => nd.Value.Name == SkillTree.CharName[tree.Chartype].ToUpper()).Value; tree.SkilledNodes.Add(startnode.Id); for (int i = 1; i < buildResp.Length; ++i) { if (!positions[int.Parse(buildResp[i])].HasValue) Debugger.Break(); Vector2D poezonePos = (positions[int.Parse(buildResp[i])].Value - new Vector2D(minx, miny))* new Vector2D(1/(maxx - minx), 1/(maxy - miny)); double minDis = 2; var minNode = new KeyValuePair<ushort, SkillNode>(); foreach (var node in SkillTree.Skillnodes) { Vector2D nodePos = (node.Value.Position - new Vector2D(nminx, nminy))* new Vector2D(1/(nmaxx - nminx), 1/(nmaxy - nminy)); double dis = (nodePos - poezonePos).Length; if (dis < minDis) { minDis = dis; minNode = node; } } tree.SkilledNodes.Add(minNode.Key); } tree.UpdateAvailNodes(); //string dataFile = }