private void EntityPropertiesGUI() { Entity singleSelectedEntity = null; if (selectedEntities.Count == 1) { singleSelectedEntity = selectedEntities[0]; } EntityReferencePropertyManager.Reset(singleSelectedEntity); // could be null and that's fine (?) GUILayout.BeginVertical(GUI.skin.box); PropertiesObjectGUI(editEntity); GUILayout.EndVertical(); if (singleSelectedEntity != null && !(singleSelectedEntity is PlayerObject)) { GUILayout.BeginHorizontal(); if (GUIUtils.HighlightedButton("Clone")) { if (singleSelectedEntity is ObjectEntity) { ObjectEntity clone = (ObjectEntity)(singleSelectedEntity.Clone()); var pickerGUI = gameObject.AddComponent <FacePickerGUI>(); pickerGUI.voxelArray = voxelArray; pickerGUI.message = "Tap to place clone"; pickerGUI.pickAction = () => { if (!voxelArray.PlaceObject(clone)) { DialogGUI.ShowMessageDialog(gameObject, ActionBarGUI.OBJECT_NO_ROOM_ERROR); } }; } else if (singleSelectedEntity is Substance) { Substance clone = (Substance)(singleSelectedEntity.Clone()); clone.defaultPaint = voxelArray.GetSelectedPaint(); clone.defaultPaint.addSelected = false; clone.defaultPaint.storedSelected = false; voxelArray.substanceToCreate = clone; var createGUI = gameObject.AddComponent <CreateSubstanceGUI>(); createGUI.voxelArray = voxelArray; } } if (GUIUtils.HighlightedButton("Delete")) { DeleteButton(); } GUILayout.EndHorizontal(); } if (selectedEntities.Count > 1) { if (GUIUtils.HighlightedButton("Delete")) { DeleteButton(); } } TutorialGUI.TutorialHighlight("change sensor"); if (GUILayout.Button("Change Sensor")) { TypePickerGUI sensorMenu = gameObject.AddComponent <TypePickerGUI>(); sensorMenu.title = "Change Sensor"; sensorMenu.categories = new PropertiesObjectType[][] { GameScripts.sensors }; sensorMenu.handler = (PropertiesObjectType type) => { foreach (Entity entity in selectedEntities) { entity.sensor = (Sensor)type.Create(); } voxelArray.unsavedChanges = true; UpdateEditEntity(); }; } TutorialGUI.ClearHighlight(); GUILayout.BeginVertical(GUI.skin.box); PropertiesObjectGUI(editSensor, " Sensor"); GUILayout.EndVertical(); TutorialGUI.TutorialHighlight("add behavior"); if (GUILayout.Button("Add Behavior")) { NewBehaviorGUI behaviorMenu = gameObject.AddComponent <NewBehaviorGUI>(); behaviorMenu.title = "Add Behavior"; behaviorMenu.self = singleSelectedEntity; behaviorMenu.voxelArray = voxelArray; behaviorMenu.handler = (PropertiesObjectType behaviorType) => { foreach (Entity entity in selectedEntities) { EntityBehavior newBehavior = (EntityBehavior)behaviorType.Create(); // with multiple selected entities, NewBehaviorGUI doesn't check if behaviors // are valid for the selected entities if (newBehavior.targetEntity.entity == null && !newBehavior.targetEntityIsActivator && !newBehavior.BehaviorObjectType().rule(entity)) { continue; } entity.behaviors.Add(newBehavior); EntityPreviewManager.BehaviorUpdated(singleSelectedEntity, newBehavior); } voxelArray.unsavedChanges = true; UpdateEditEntity(); scrollVelocity = new Vector2(0, 2000 * editBehaviors.Count); // scroll to bottom }; } TutorialGUI.ClearHighlight(); Color guiBaseColor = GUI.backgroundColor; StoredEntityBehavior behaviorToRemove = null; foreach (StoredEntityBehavior storedBehavior in editBehaviors) { TutorialGUI.TutorialHighlight("behaviors"); Entity behaviorTarget = null; if (storedBehavior.sharedTarget) { behaviorTarget = storedBehavior.allBehaviors[0].targetEntity.entity; } if (behaviorTarget != null) { EntityReferencePropertyManager.Next(behaviorTarget); GUI.backgroundColor = guiBaseColor * EntityReferencePropertyManager.GetColor(); } EntityReferencePropertyManager.SetBehaviorTarget(behaviorTarget); GUILayout.BeginVertical(GUI.skin.box); GUI.backgroundColor = guiBaseColor; PropertiesObjectGUI(storedBehavior, " Behavior", () => EntityPreviewManager.BehaviorUpdated(singleSelectedEntity, storedBehavior.allBehaviors[0])); if (GUILayout.Button("Remove")) { behaviorToRemove = storedBehavior; } GUILayout.EndVertical(); // clear this every time, in case the next target is the same EntityReferencePropertyManager.SetBehaviorTarget(null); } if (behaviorToRemove != null) { foreach (Entity entity in selectedEntities) { foreach (EntityBehavior remove in behaviorToRemove.allBehaviors) { if (entity.behaviors.Remove(remove)) { break; } } } voxelArray.unsavedChanges = true; UpdateEditEntity(); EntityPreviewManager.BehaviorUpdated(singleSelectedEntity, behaviorToRemove.allBehaviors[0]); } if (mismatchedSelectedBehaviorCounts) { GUILayout.BeginVertical(GUI.skin.box); GUILayout.Label("(other behaviors...)", GUI.skin.GetStyle("label_title")); GUILayout.EndVertical(); } }
/// <summary> /// Draws the rule inspector. /// </summary> /// <param name='obj'> /// Object - the serialized object /// </param> private void DrawRuleInspector(Object obj) { SerializedObject serObj = new SerializedObject(obj); //rule row - enable/disable rule foldout + reset button Rect ruleTopRect = EditorGUILayout.BeginHorizontal(); { Rect imageRect = new Rect(ruleTopRect); imageRect.width = 20; imageRect.x = 35; Texture2D icon = (Texture2D)Resources.Load(((BaseRule)obj).GetIconPath()); if (icon != null) { EditorGUI.DrawPreviewTexture(imageRect, (Texture2D)Resources.Load(((BaseRule)obj).GetIconPath())); } ((BaseRule)obj).IsEnabled = EditorGUILayout.Toggle(((BaseRule)obj).Enabled, GUILayout.Width(30)); GUIContent placeHolderContent = new GUIContent("", ((BaseRule)obj).GetRuleDescription()); string[] ver = UnityEditorInternal.InternalEditorUtility.GetFullUnityVersion().Substring(0, 5).Replace('.', ' ').Split(' '); if (int.Parse(ver[0]) == 4 && int.Parse(ver[1]) <= 2) { EditorGUILayout.LabelField(placeHolderContent, GUILayout.Width(25)); } else { EditorGUILayout.LabelField(placeHolderContent, GUILayout.Width(0)); } ((BaseRule)obj).FoldoutOpen = GUIUtils.Foldout(((BaseRule)obj).FoldoutOpen, new GUIContent(((BaseRule)obj).FriendlyName, ((BaseRule)obj).GetRuleDescription())); } EditorGUILayout.EndHorizontal(); SetRulesContextMenu(ruleTopRect, (BaseRule)obj); if (((BaseRule)obj).FoldoutOpen) { EditorGUI.indentLevel++; EditorGUI.indentLevel++; EditorGUI.indentLevel++; if (serObj != null) { SerializedProperty prop = serObj.GetIterator(); prop.NextVisible(true); do { if (prop.name != "m_Script" && prop.name != "Enabled") { EditorGUILayout.PropertyField(prop, true); } } while (prop.NextVisible(false)); prop.Reset(); } else { EditorGUILayout.PrefixLabel("Rule Null "); } EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUI.indentLevel--; } if (GUI.changed) { EditorUtility.SetDirty(serObj.targetObject); } //save changes to serialized object serObj.ApplyModifiedProperties(); }
private void Start() { var crosshairTexture = (Texture2D)null; // BaseEngine.instance.Asset.LoadTexture("target", true); _crosshair.sprite = GUIUtils.CreateSprite(crosshairTexture); }
/// <summary> /// Construct a view with the given options /// </summary> public ChoiceView(IEnumerable <string> optionsStrings) : base() { var options = optionsStrings.ToIArray(); // we'll use this tooltip to display mouseover shortcuts for the buttons var tooltip = this.RegisterDisposable(new ToolTip()); // a panel to hold all controls created by the view var panel = this.RegisterDisposable(new Panel() { Dock = DockStyle.Fill }); // a table to hold the buttons (TODO change this to use the GUIUtils convenience methods for creating tables) var table = new TableLayoutPanel() { Dock = DockStyle.Fill, RowCount = 1, ColumnCount = options.Count }; // a list of the click-handler functions for each button var handlerList = new List <KeyPressEventHandler>(); // this variable will later be filled in with the current form Form form = null; // create each button for (int i = 0; i < table.ColumnCount; i++) { // divide the width equally between all buttons table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 1.0f / table.ColumnCount)); // create a button for the option var button = GUIUtils.CreateFlatButton( options[i], // when the button is clicked, set this view's result to the text of the button and finish b => { this.SetResult(b.Text); this.Finish(); }, tooltip, // the mouseover text depends on the current index i < HOME_ROW.Length ? "Shortcut: " + HOME_ROW[i] : "No shortcut" ); button.Font = GUIUtils.Constants.DISPLAY_FONT; // register a keypad shortcut if (i < HOME_ROW.Length) { char keyChar = HOME_ROW[i]; handlerList.Add((sender, args) => { // when the key for the button is pressed, fire a button click event if (args.KeyChar == keyChar) { button.PerformClick(); } }); } // ensures that the buttons don't steal the form's key-presses! // unfortunately, both of these "solutions" seem to cause other issues, so they're staying commented out //button.KeyPress += (sender, args) => handlerList.ForEach(h => h(form ?? sender, args)); //button.GotFocus += (sender, args) => button.FindForm().Focus(); button.KeyPress += handlerList.LastItem(); // add the button to the table table.Controls.Add(button, i, 0); } /* * This is just here so that we can register the keypad shortcuts at the form level. * There's no form available when the view is being constructed, but when it's being displayed * we can find one with the FindForm() method. The paint event won't be fired until that point */ table.Paint += (sender, args) => { // don't do anything if we've already found a form or can't find one if (form != null || (form = table.FindForm()) == null) { return; } // register our key press handlers with the form foreach (var handler in handlerList) { form.KeyPress += handler; } }; // when the view finishes, we need to un-register the key press handlers so they don't affect future views this.DoOnFinishing(() => { if (form != null) { foreach (var handler in handlerList) { form.KeyPress -= handler; } } }); // add the button table to the panel panel.Controls.Add(table); // create a label to display the view's text, if there is any var label = this.RegisterDisposable(new Label() { Dock = DockStyle.Top, TextAlign = System.Drawing.ContentAlignment.MiddleCenter, Font = GUIUtils.Constants.DISPLAY_FONT }); // when the view deploys, install its controls this.DoOnDeploy(c => { // if we have text to display, set up the label. We can't do this before deploying because // the text property can be changed between calling the view constructor and deploying the // view if (!string.IsNullOrEmpty(this.Text)) { label.Text = this.Text; panel.Controls.Add(label); } // add the panel to the control c c.Controls.Add(panel); }); }
private void AeroDataTab(GUIStyle buttonStyle, GUIStyle boxStyle) { int i = 0; GUILayout.BeginVertical(boxStyle); FARControllableSurface.timeConstant = GUIUtils.TextEntryForDouble("Ctrl Surf Time Constant:", 160, FARControllableSurface.timeConstant); FARControllableSurface.timeConstantFlap = GUIUtils.TextEntryForDouble("Flap Time Constant:", 160, FARControllableSurface.timeConstantFlap); FARControllableSurface.timeConstantSpoiler = GUIUtils.TextEntryForDouble("Spoiler Time Constant:", 160, FARControllableSurface.timeConstantSpoiler); GUILayout.EndVertical(); GUILayout.BeginVertical(); GUILayout.Label("Celestial Body Atmosperic Properties"); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(boxStyle); GUILayout.BeginHorizontal(); int j = 0; for (i = 0; i < FlightGlobals.Bodies.Count; i++) { CelestialBody body = FlightGlobals.Bodies[i]; if (!body.atmosphere) { continue; } bool active = GUILayout.Toggle(i == atmBodyIndex, body.GetName(), buttonStyle, GUILayout.Width(150), GUILayout.Height(40)); if (active) { atmBodyIndex = i; } if ((j + 1) % 4 == 0) { GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); } j++; } GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.BeginVertical(boxStyle); int flightGlobalsIndex = FlightGlobals.Bodies[atmBodyIndex].flightGlobalsIndex; double[] atmProperties = FARAeroUtil.bodyAtmosphereConfiguration[flightGlobalsIndex]; atmProperties[0] = GUIUtils.TextEntryForDouble("Gas Viscosity:", 80, atmProperties[0]); atmProperties[1] = GUIUtils.TextEntryForDouble("Ref Temp for Viscosity:", 80, atmProperties[1]); FARAeroUtil.bodyAtmosphereConfiguration[flightGlobalsIndex] = atmProperties; GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); }
private void BuildView() { // config panel var config = ConfigurationPanel.Create <ExperimentSettings>(); // output folder var outputLabel = "Data Output Folder".ToLabel(DockStyle.Bottom); var outputLink = new LinkLabel() { Text = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Dock = DockStyle.Bottom }; outputLink.Click += (sender, args) => { if (this.folderDialog.ShowDialog() != DialogResult.OK) { return; } outputLink.Text = this.folderDialog.SelectedPath; }; this.getExperimentSettings = () => { var settings = (ExperimentSettings)config.GetConfiguredObject(); settings.OutputFolder = outputLink.Text; return(settings); }; // button table var buttonTable = GUIUtils.CreateButtonTable(Direction.Horizontal, DockStyle.Bottom, GUIUtils.CreateFlatButton("Save", b => { var settings = this.ExperimentSettings; this.saveDialog.FileName = string.IsNullOrWhiteSpace(settings.ExperimentName) ? "my experiment" : settings.ExperimentName; if (this.saveDialog.ShowDialog() != DialogResult.OK) { return; } bool saved = settings.TrySerializeToFile(this.saveDialog.FileName); GUIUtils.Alert((saved ? "Saved" : "Failed to save") + " experiment info to " + this.saveDialog.FileName, (saved ? MessageBoxIcon.Information : MessageBoxIcon.Error)); string directory = Path.GetDirectoryName(this.saveDialog.FileName); if (Directory.Exists(directory)) { this.saveDialog.InitialDirectory = directory; } }, this.toolTip, "Save experiment configuration information"), GUIUtils.CreateFlatButton("Load", b => { if (this.openDialog.ShowDialog() != DialogResult.OK) { return; } ExperimentSettings settings; foreach (var path in this.openDialog.FileNames) { if (Utils.TryDeserializeFile(this.openDialog.FileName, out settings)) { config.SetConfiguredObject(settings); } else { GUIUtils.Alert("Failed to load experiment info from " + path, MessageBoxIcon.Error); } } }, this.toolTip, "Load a previously saved experiment settings file")); // add all controls this.Controls.Add(config); this.Controls.Add(outputLabel); this.Controls.Add(outputLink); this.Controls.Add(buttonTable); }
void Start() { // adjust rect this.windowRect = GUIUtils.GetCenteredRect(new Vector2(550, 300)); }
public static bool ItemTransferValidNew(InventoryItem invitem, UIInventoryGridItem from, UIInventoryGridItem to, out string error) { error = string.Empty; if ((invitem == null) || (invitem.baseItem == null)) { return(true); } if ((@from == to) && UIGlobalInventory.Instance.DragOwnerIsSame()) { return(true); } if (!ItemTransferValid(invitem, @from, to.Owner, out error)) { return(false); } // this is to disallow items TO // added code if (IEModOptions.UnlockCombatInv && GameState.InCombat && (to.EquipmentSlot == Equippable.EquipmentSlot.Armor || ForbiddenToMoveItems.Contains(invitem.BaseItem.Name))) // added this line { error = GUIUtils.GetText(0xd7); return(false); // added this line // doesn't allow equipping/unequipping armor during combat, as well as summoned magical items such as druid cat claws } // end of added code if ((to.Locked || to.Blocked) || !to.EquipmentModifyValid()) { return(false); } if (to.EquipmentSlot != Equippable.EquipmentSlot.None) { error = GUIUtils.GetText(0xd9); Equippable baseItem = invitem.baseItem as Equippable; if (baseItem == null) { return(false); } if (!baseItem.CanUseSlot(to.EquipmentSlot)) { return(false); } if ((to.WeaponSetBuddy != null) && !to.WeaponSetBuddy.Empty) { if (baseItem.BothPrimaryAndSecondarySlot) { error = GUIUtils.GetText(0x6c9); return(false); } Equippable equippable2 = to.WeaponSetBuddy.InvItem.baseItem as Equippable; if ((equippable2 != null) && equippable2.BothPrimaryAndSecondarySlot) { error = GUIUtils.GetText(0x6c9); return(false); } } Equipment selectedEquipment = UIInventoryManager.Instance.Equipment.SelectedEquipment; if ((selectedEquipment != null) && selectedEquipment.IsSlotLocked(to.EquipmentSlot)) { return(false); } if (!baseItem.CanEquip(UIInventoryManager.Instance.SelectedCharacter.gameObject)) { CharacterStats selectedCharacter = UIInventoryManager.Instance.SelectedCharacter; object[] parameters = new object[] { invitem.baseItem.Name, GUIUtils.GetClassString(selectedCharacter.CharacterClass, selectedCharacter.Gender) }; error = GUIUtils.Format(0x3eb, parameters); return(false); } } if (@from.EquipmentSlot != Equippable.EquipmentSlot.None) { Equipment equipment2 = UIInventoryManager.Instance.Equipment.SelectedEquipment; if ((equipment2 != null) && equipment2.IsSlotLocked(to.EquipmentSlot)) { return(false); } } if ((to.EquipmentSlot == Equippable.EquipmentSlot.Grimoire) && (UIInventoryManager.Instance.SelectedCharacter.SpellCastingDisabled > 0)) { error = GUIUtils.GetText(0x6ca); return(false); } if (((to.RestrictByFilter != UIInventoryFilter.ItemFilterType.NONE) && ((invitem.baseItem.FilterType & to.RestrictByFilter) == UIInventoryFilter.ItemFilterType.NONE)) && (((to.OrAllowEquipment == Equippable.EquipmentSlot.None) || !(invitem.baseItem is Equippable)) || !(invitem.baseItem as Equippable).CanUseSlot(to.OrAllowEquipment))) { return(false); } return(true); }
public override void DoWindowContents(Rect inRect) { float y = inRect.y + 10; Text.Anchor = TextAnchor.MiddleCenter; Rect selectFactionRect = new Rect(0, y, inRect.width, 25); if (GUIUtils.DrawCustomButton(selectFactionRect, "DefenseContractCompWindow_SelectFaction".Translate(faction.Faction.Name), Color.white)) { List <FloatMenuOption> opt = new List <FloatMenuOption>(); foreach (var f in alliance.Factions) { opt.Add(new FloatMenuOption($"{f.Faction.Name} {((int)f.Faction.def.techLevel < (int)defenseContractCompProperties.MinFactionTechLevel ? "DefenseContractCompWindow_LowTechLevel".Translate().ToString() : "")}", () => { if ((int)f.Faction.def.techLevel > (int)defenseContractCompProperties.MinFactionTechLevel) { faction = f; } })); } Find.WindowStack.Add(new FloatMenu(opt)); } y += 30; Rect durationLabelRect = new Rect(0, y, inRect.width, 30); Widgets.Label(durationLabelRect, "DefenseContractCompWindow_ContractDuration".Translate()); durationLabelRect.y += 30; Widgets.IntEntry(durationLabelRect, ref contractDaysDuration, ref contractDaysDurationBuff); if (contractDaysDuration < minContractDays) { ResetBufferTo(minContractDays, ref contractDaysDuration, ref contractDaysDurationBuff); } else if (contractDaysDuration > maxContractDays) { ResetBufferTo(maxContractDays, ref contractDaysDuration, ref contractDaysDurationBuff); } y = 100; Rect costRangeRect = new Rect(0, y, inRect.width, 25); Widgets.Label(costRangeRect, "DefenseContractCompWindow_CostRangeSlider".Translate()); costRangeRect.y += 28; if (GUIUtils.DrawCustomButton(costRangeRect, fightersType.ToStringHuman(), Color.white)) { List <FloatMenuOption> opt = new List <FloatMenuOption>(); foreach (FightersLevel f in Enum.GetValues(typeof(FightersLevel))) { opt.Add(new FloatMenuOption(f.ToStringHuman(), () => fightersType = f)); } Find.WindowStack.Add(new FloatMenu(opt)); } y += 60; Rect generateButtonRect = new Rect(0, y, inRect.width, 25); if (GUIUtils.DrawCustomButton(generateButtonRect, "DefenseContractCompWindow_ShowExamplePawns".Translate(), Color.white)) { GenerateAndSelectPawns(); } y += 30; Widgets.DrawLineHorizontal(0, y, inRect.width); y += 35; Rect pawnRect = new Rect(0, y, 100, 140); float weaponY = pawnRect.y + 135; Rect weaponRect = new Rect(0, weaponY, 100, 100); foreach (var pawn in generatedPawns) { Widgets.ThingIcon(pawnRect, pawn); if (pawn.equipment != null && pawn.equipment.Primary != null) { Widgets.ThingIcon(weaponRect, pawn.equipment.Primary); } weaponRect.x += 110; pawnRect.x += 110; } Text.Anchor = TextAnchor.UpperLeft; y += 280; Rect infoRect = new Rect(0, y, inRect.width, 200); Widgets.Label(infoRect, "DefenseContractCompWindow_ResultInfo".Translate(contractDaysDuration, totalDaysCost, fightersType.ToStringHuman(), fightersCost[fightersType], totalCost)); Text.Anchor = TextAnchor.MiddleCenter; y += 210; Rect createAgrRect = new Rect(0, inRect.height - 30, inRect.width, 25); bool active = faction.Trust >= totalCost; if (GUIUtils.DrawCustomButton(createAgrRect, "DefenseContractCompWindow_CreateAgreement".Translate(), active ? Color.white : Color.gray)) { if (active) { CreateAgreement(); Close(); } else { Messages.Message("DefenseContractCompWindow_CreateAgreement_NoTrust".Translate(), MessageTypeDefOf.NegativeEvent, false); } } Text.Anchor = TextAnchor.UpperLeft; }
public void drawInspector() { if (GUIUtils.DrawHeader("Create palette")) { GUIUtils.BeginContents(); { EditorGUILayout.BeginHorizontal(); { m_selectedAlgorithm = (Algorithm)EditorGUILayout.EnumPopup(m_selectedAlgorithm); if (GUILayout.Button("Generate", EditorStyles.miniButton)) { GUI.FocusControl(null); generatePalette(); } } EditorGUILayout.EndHorizontal(); m_colorCount = EditorGUILayout.IntSlider("Number of colors", m_colorCount, 1, 25); if (m_selectedAlgorithm == Algorithm.RANDOM_FROM_COLOR) { m_colorReference = EditorGUILayout.ColorField("Base color", m_colorReference); m_colorOffset = EditorGUILayout.FloatField("Color offset", m_colorOffset); } else if (m_selectedAlgorithm == Algorithm.RANDOM_GOLDEN_RATIO) { m_saturation = EditorGUILayout.Slider("Saturation", m_saturation, 0.0f, 1.0f); } else if (m_selectedAlgorithm == Algorithm.GRADIENT) { m_colorGradient1 = EditorGUILayout.ColorField("From color", m_colorGradient1); m_colorGradient2 = EditorGUILayout.ColorField("To color", m_colorGradient2); } if (m_generatedColorPalette != null) { if (GUI.changed) { generatePalette(); } GUILayout.Space(3f); EditorGUILayout.BeginHorizontal(); { for (int j = 0; j < m_generatedColorPalette.colorInfoList.Count; j++) { Rect rect = EditorGUILayout.GetControlRect(false, 20f, EditorStyles.colorField, GUILayout.Width(20f)); EditorGUIUtility.DrawColorSwatch(rect, m_generatedColorPalette.colorInfoList[j].color); } } EditorGUILayout.EndHorizontal(); GUILayout.Space(3f); if (GUILayout.Button("Add to my palettes")) { m_paletteData.colorPaletteList.Add(m_generatedColorPalette); m_generatedColorPalette = null; PaletteUtils.SavePalettes(m_paletteData); } } } GUIUtils.EndContents(); } }
/// <summary> /// Shows the Rate Dialog after playback has ended /// </summary> /// <param name="episode">The item being rated</param> private void ShowRateDialog(ITrackingInfo videoInfo) { if (!TraktSettings.ShowRateDialogOnWatched) { return; } var rateThread = new Thread((objInfo) => { var itemToRate = objInfo as ITrackingInfo; if (itemToRate == null) { return; } int rating = -1; if (itemToRate.VideoKind == VideoKind.TvSeries) { TraktLogger.Info("Showing rate dialog for episode. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}', Season = '{4}', Episode = '{5}'", itemToRate.Title, itemToRate.Year == 0 ? "<empty>" : itemToRate.Year.ToString(), itemToRate.ID_IMDB.ToLogString(), itemToRate.ID_TMDB.ToLogString(), itemToRate.Episode, itemToRate.Season); // this gets complicated when the episode IDs are not available! var rateObject = new TraktSyncShowRatedEx { Ids = new TraktShowId { Tvdb = itemToRate.ID_TVDB.ToNullableInt32(), Tmdb = itemToRate.ID_TMDB.ToNullableInt32() }, Title = itemToRate.Title, Year = itemToRate.Year > 0 ? (int?)itemToRate.Year : null, Seasons = new List <TraktSyncShowRatedEx.Season> { new TraktSyncShowRatedEx.Season { Number = (int)itemToRate.Season, Episodes = new List <TraktSyncShowRatedEx.Season.Episode> { new TraktSyncShowRatedEx.Season.Episode { Number = (int)itemToRate.Episode, RatedAt = DateTime.UtcNow.ToISO8601() } } } } }; // get the rating submitted to trakt rating = GUIUtils.ShowRateDialog <TraktSyncShowRatedEx>(rateObject); // add episode rated to cache if (rating > 0) { TraktCache.AddEpisodeToRatings( new TraktShow { Ids = rateObject.Ids, Title = rateObject.Title, Year = rateObject.Year, }, new TraktEpisode { Ids = new TraktEpisodeId(), Season = rateObject.Seasons[0].Number, Number = rateObject.Seasons[0].Episodes[0].Number }, rating ); } } else if (itemToRate.VideoKind == VideoKind.Movie) { TraktLogger.Info("Showing rate dialog for movie. Title = '{0}', Year = '{1}', IMDb Id = '{2}', TMDb ID = '{3}'", itemToRate.Title, itemToRate.Year, itemToRate.ID_IMDB.ToLogString(), itemToRate.ID_TMDB.ToLogString()); var rateObject = new TraktSyncMovieRated { Ids = new TraktMovieId { Imdb = itemToRate.ID_IMDB, Tmdb = itemToRate.ID_TMDB.ToNullableInt32() }, Title = itemToRate.Title, Year = (int)itemToRate.Year, RatedAt = DateTime.UtcNow.ToISO8601() }; // get the rating submitted to trakt rating = GUIUtils.ShowRateDialog <TraktSyncMovieRated>(rateObject); // add movie rated to cache if (rating > 0) { TraktCache.AddMovieToRatings(rateObject, rating); } else { TraktCache.RemoveMovieFromRatings(rateObject); } } }) { Name = "Rate", IsBackground = true }; rateThread.Start(videoInfo); }
public void DisplaySelection() { GUILayout.BeginVertical(); GUILayout.Label("Transonic Drag Settings"); GUILayout.Label("Absolute magnitude of drag can be scaled, as can how lenient FAR is about enforcing proper area ruling."); GUILayout.BeginHorizontal(); if (currentIndex >= 0) { dropdown.GUIDropDownDisplay(GUILayout.Width(300)); settings = dropdown.ActiveSelection; currentIndex = settings.index; } else { GUILayout.BeginVertical(); settings = customSettings; settings.fractionTransonicDrag = GUIUtils.TextEntryForDouble("Frac Mach 1 Drag: ", 150, settings.fractionTransonicDrag); GUILayout.Label("The below are used in controlling leniency of design. Higher values for all will result in more leniency"); settings.gaussianVehicleLengthFractionForSmoothing = GUIUtils.TextEntryForDouble("% Vehicle Length for Smoothing", 250, settings.gaussianVehicleLengthFractionForSmoothing); settings.numAreaSmoothingPasses = GUIUtils.TextEntryForInt("Smoothing Passes, Cross-Sectional Area", 250, settings.numAreaSmoothingPasses); if (settings.numAreaSmoothingPasses < 0) { settings.numAreaSmoothingPasses = 0; } settings.numDerivSmoothingPasses = GUIUtils.TextEntryForInt("Smoothing Passes, area 2nd deriv", 250, settings.numDerivSmoothingPasses); if (settings.numDerivSmoothingPasses < 0) { settings.numDerivSmoothingPasses = 0; } customSettings = settings; GUILayout.EndVertical(); } if (GUILayout.Button(currentIndex < 0 ? "Switch Back To Presets" : "Choose Custom Settings")) { if (currentIndex >= 0) { currentIndex = -1; } else { currentIndex = 4; } } GUILayout.EndHorizontal(); GUILayout.Label("Voxel Detail Settings; increasing these will improve accuracy at the cost of performance"); voxelSettings.numVoxelsControllableVessel = GUIUtils.TextEntryForInt("Voxels Controllable Vessel: ", 200, voxelSettings.numVoxelsControllableVessel); if (voxelSettings.numVoxelsControllableVessel < 0) { voxelSettings.numVoxelsControllableVessel = 100000; } voxelSettings.numVoxelsDebrisVessel = GUIUtils.TextEntryForInt("Voxels Debris: ", 200, voxelSettings.numVoxelsDebrisVessel); if (voxelSettings.numVoxelsDebrisVessel < 0) { voxelSettings.numVoxelsDebrisVessel = 5000; } voxelSettings.minPhysTicksPerUpdate = GUIUtils.TextEntryForInt("Min Phys Ticks per Voxel Update: ", 200, voxelSettings.minPhysTicksPerUpdate); if (voxelSettings.minPhysTicksPerUpdate < 0) { voxelSettings.minPhysTicksPerUpdate = 80; } GUILayout.BeginHorizontal(); GUILayout.Label("Use Higher Res SubVoxels: "); voxelSettings.useHigherResVoxelPoints = GUILayout.Toggle(voxelSettings.useHigherResVoxelPoints, voxelSettings.useHigherResVoxelPoints ? "High Res SubVoxels" : "Low Res SubVoxels"); GUILayout.EndHorizontal(); GUILayout.EndVertical(); }
public void mod_AdjustDamageDealt(GameObject enemy, DamageInfo damage, bool testing) { float statDamageHealMultiplier = this.StatDamageHealMultiplier; damage.DamageMult(statDamageHealMultiplier); if (!testing && this.OnPreDamageDealt != null) { this.OnPreDamageDealt(base.gameObject, new CombatEventArgs(damage, base.gameObject, enemy)); } if (!testing && this.OnAddDamage != null) { this.OnAddDamage(base.gameObject, new CombatEventArgs(damage, base.gameObject, enemy)); } int attackerToHitRollOverride = Random.Range(1, 101); CharacterStats component = enemy.GetComponent <CharacterStats>(); if (component == null) { return; } attackerToHitRollOverride = component.GetAttackerToHitRollOverride(attackerToHitRollOverride); int num = this.CalculateAccuracy(damage.Attack, enemy); bool flag = component.CalculateIsImmune(damage.DefendedBy, damage.Attack, base.gameObject); int num1 = component.CalculateDefense(damage.DefendedBy, damage.Attack, base.gameObject); if (damage.DefendedBy != CharacterStats.DefenseType.None) { this.ComputeHitAdjustment(attackerToHitRollOverride + num - num1, component, damage); //!+ ADDED CODE if (IEModOptions.DisableFriendlyFire) { var faction = enemy.Component <Faction>(); if (faction.IsFriendly(base.gameObject) && base.IsPartyMember && faction.isPartyMember) { damage.IsCriticalHit = false; damage.Interrupts = false; damage.IsGraze = false; damage.IsKillingBlow = false; damage.IsMiss = true; } } //!+ END ADD if (!testing && this.OnAttackRollCalculated != null) { this.OnAttackRollCalculated(base.gameObject, new CombatEventArgs(damage, base.gameObject, enemy)); } if (damage.IsCriticalHit) { float criticalHitMultiplier = this.CriticalHitMultiplier; Health health = enemy.GetComponent <Health>(); if (health != null && health.StaminaPercentage < 0.1f) { criticalHitMultiplier = criticalHitMultiplier + this.CritHitDamageMultiplierBonusEnemyBelow10Percent; } damage.DamageMult(criticalHitMultiplier); } else if (damage.IsGraze) { damage.DamageMult(CharacterStats.GrazeMultiplier); } else if (damage.IsMiss) { damage.DamageMult(0f); } } WeaponSpecializationData.AddWeaponSpecialization(this, damage); damage.AccuracyRating = num; damage.DefenseRating = num1; damage.Immune = flag; damage.RawRoll = attackerToHitRollOverride; if (!testing && damage.Immune) { UIHealthstringManager.Instance.ShowNotice(GUIUtils.GetText(2188), enemy, 1f); } if (!testing && this.OnAdjustCritGrazeMiss != null) { this.OnAdjustCritGrazeMiss(base.gameObject, new CombatEventArgs(damage, base.gameObject, enemy)); } if (!damage.IsMiss) { if (damage.Attack.IsDisengagementAttack) { damage.DamageAdd(this.DisengagementDamageBonus * statDamageHealMultiplier); } if (damage.Attack is AttackMelee) { damage.DamageMult(this.BonusMeleeDamageMult); damage.DamageAdd(this.BonusMeleeDamage * statDamageHealMultiplier); if ((damage.Attack as AttackMelee).Unarmed) { damage.DamageAdd(this.BonusUnarmedDamage * statDamageHealMultiplier); } } for (int i = 0; i < (int)this.BonusDamage.Length; i++) { if (this.BonusDamage[i] != 0f) { DamagePacket.DamageProcType damageProcType = new DamagePacket.DamageProcType((DamagePacket.DamageType)i, this.BonusDamage[i]); damage.Damage.DamageProc.Add(damageProcType); } } this.AddBonusDamagePerType(damage); this.AddBonusDamagePerRace(damage, component); if (damage.Attack != null) { Equippable equippable = damage.Attack.GetComponent <Equippable>(); if (equippable != null) { if (equippable is Weapon) { if (!(damage.Attack is AttackMelee)) { damage.DamageMult(this.BonusRangedWeaponDamageMult); if (enemy != null && !this.IsEnemyDistant(enemy)) { damage.DamageMult(this.BonusRangedWeaponCloseEnemyDamageMult); } } else { damage.DamageMult(this.BonusMeleeWeaponDamageMult); if (equippable.BothPrimaryAndSecondarySlot) { damage.DamageMult(this.BonusTwoHandedMeleeWeaponDamageMult); } } } equippable.ApplyItemModDamageProcs(damage); } } } this.ComputeInterrupt(component, damage); if (!testing && this.IsPartyMember) { if (component) { component.RevealDefense(damage.DefendedBy); component.RevealDT(damage.Damage.Type); foreach (DamagePacket.DamageProcType damageProc in damage.Damage.DamageProc) { component.RevealDT(damageProc.Type); } } if (damage.DefenseRating >= damage.AccuracyRating + 50 || damage.Immune) { GameState.AutoPause(AutoPauseOptions.PauseEvent.ExtraordinaryDefence, base.gameObject, enemy, null); TutorialManager.STriggerTutorialsOfTypeFast(TutorialManager.ExclusiveTriggerType.PARTYMEM_GETS_DEFENSE_TOO_HIGH); } } if (!testing && this.OnPostDamageDealt != null) { this.OnPostDamageDealt(base.gameObject, new CombatEventArgs(damage, base.gameObject, enemy)); } }
// Expose GUIUtils methods so they can be used without instance prefix public static void AllButtonsState(GUI g, bool visible, bool clickable) { GUIUtils.AllButtonsState(g, visible, clickable); }
public static bool IsWithinViewport(Camera camera, GameObject gameObject) { var viewportBounds = GUIUtils.GetViewportBoundsFromViewport(camera, new Vector2(0, 0), new Vector2(1, 1)); return(viewportBounds.Contains(camera.WorldToViewportPoint(gameObject.transform.position))); }
public void DrawWindow(int id) { GUI.DragWindow(new Rect(0, 0, 348, 28)); if (GUIUtils.CloseHelpButtons(window, "Asset_Creator_Helper")) { showUI = false; editingType = string.Empty; editingProp = null; editingBuilding = null; allVertices = null; dependencyGroups = new List <DependencyGroup>(); lockedVertices = new List <Vertex>(); selectedDependencyGroup = null; scrollGroups = Vector2.zero; } if (selectedDependencyGroup == null) { #region main panel GUI.Label(new Rect(10, 30, 350, 30), "Dependency Groups"); GUI.Box(new Rect(5, 58, 390, 302), string.Empty); scrollGroups = GUI.BeginScrollView(new Rect(10, 60, 350, 295), scrollGroups, new Rect(0, 0, 320, 35 * dependencyGroups.Count())); for (int i = 0; i < dependencyGroups.Count(); i++) { if (GUI.Button(new Rect(10, i * 33 + 2, 300, 33), "Group " + (i + 1).ToString())) { selectedDependencyGroup = dependencyGroups[i]; } } GUI.EndScrollView(); if (GUI.Button(new Rect(10, 422, 185, 25), "Save Data in Asset")) { // saving process string data = ProceduralObjectAssetUtils.SaveDependencyData(dependencyGroups, lockedVertices); if (editingType == "PROP") { editingProp.m_material.name = data; } else { editingBuilding.m_material.name = data; } Debug.Log("[ProceduralObjects] Saved the following data in asset : " + data); showUI = false; editingProp = null; editingBuilding = null; allVertices = null; dependencyGroups = new List <DependencyGroup>(); lockedVertices = new List <Vertex>(); selectedDependencyGroup = null; scrollGroups = Vector2.zero; } if (GUI.Button(new Rect(205, 422, 185, 25), "Create Dependency Group")) { var group = new DependencyGroup(); dependencyGroups.Add(group); selectedDependencyGroup = group; settingMainVertex = true; } #endregion } else if (selectedDependencyGroup != null) { #region group editor if (settingMainVertex) { GUI.Label(new Rect(50, 270, 380, 80), "Select a new main vertex"); } else { if (GUI.Button(new Rect(10, 100, 380, 80), "Delete Group")) { dependencyGroups.Remove(selectedDependencyGroup); selectedDependencyGroup = null; useRegion = false; topLeftRegion = Vector2.zero; bottomRightRegion = Vector2.zero; } if (GUI.Button(new Rect(10, 270, 380, 80), "OK")) { selectedDependencyGroup = null; useRegion = false; topLeftRegion = Vector2.zero; bottomRightRegion = Vector2.zero; } if (GUI.Button(new Rect(10, 185, 380, 80), "Change main vertex")) { settingMainVertex = true; useRegion = false; topLeftRegion = Vector2.zero; bottomRightRegion = Vector2.zero; } useRegion = GUI.Toggle(new Rect(30, 360, 350, 30), useRegion, "Use Mouse Region selection"); } #endregion } }
public void ShowInteractiveText(GenericObjectComponent component) { var data = component.objData; _uiManager.InteractiveText.Show(GUIUtils.CreateSprite(data.icon), data.interactionPrefix, data.name, data.value, data.weight); }
void OnGUI() { if (ProceduralObjectsMod.ShowDeveloperTools.value) { if (clickingRegion && useRegion) { GUI.Box(CreateRectFromVector2s(topLeftRegion, bottomRightRegion), ""); } if (!showUI) { if (GUI.Button(new Rect(Screen.width - 200, 60, 195, 30), "Procedural Obj Helper")) { try { if (ToolsModifierControl.toolController.m_editPrefabInfo.GetType() == typeof(PropInfo)) { editingType = "PROP"; editingProp = ToolsModifierControl.toolController.m_editPrefabInfo as PropInfo; allVertices = Vertex.CreateVertexList(editingProp); showUI = true; } else if (ToolsModifierControl.toolController.m_editPrefabInfo.GetType() == typeof(BuildingInfo)) { editingType = "BUILDING"; editingBuilding = ToolsModifierControl.toolController.m_editPrefabInfo as BuildingInfo; allVertices = Vertex.CreateVertexList(editingBuilding); showUI = true; } } catch { } } } else { window = GUIUtils.Window(this.GetInstanceID(), window, DrawWindow, "Procedural Objects Asset Creator Helper"); if (settingMainVertex) { #region when user is Setting the MAIN VERTEX foreach (Vertex vertex in allVertices.Where(v => !v.IsDependent)) { if (!DependencyGroup.AlreadyBelongsToAGroup(vertex, dependencyGroups, true, selectedDependencyGroup) && !lockedVertices.Contains(vertex)) { if (selectedDependencyGroup.mainVertex != vertex) { if (GUI.Button(new Rect((vertex.Position + levelVector).WorldToGuiPoint() + new Vector2(-11, -11), new Vector2(23, 22)), "<size=20>+</size>")) { if (selectedDependencyGroup.subVertices.Contains(vertex)) { selectedDependencyGroup.subVertices.Add(selectedDependencyGroup.mainVertex); selectedDependencyGroup.mainVertex = vertex; selectedDependencyGroup.subVertices.Remove(vertex); settingMainVertex = false; } else { selectedDependencyGroup.mainVertex = vertex; settingMainVertex = false; } } } } } #endregion } else if (selectedDependencyGroup != null) { #region vertex edit tool foreach (Vertex vertex in allVertices.Where(v => !v.IsDependent)) { if (!DependencyGroup.AlreadyBelongsToAGroup(vertex, dependencyGroups, true, selectedDependencyGroup) && !lockedVertices.Contains(vertex)) { if (selectedDependencyGroup.mainVertex == vertex) { GUI.contentColor = Color.red; GUI.Label(new Rect((vertex.Position + levelVector).WorldToGuiPoint() + new Vector2(-8, -8), new Vector2(23, 22)), "<size=20><b>X</b></size>"); GUI.contentColor = Color.white; } else if (selectedDependencyGroup.subVertices.Contains(vertex)) { GUI.contentColor = Color.green; if (GUI.Button(new Rect((vertex.Position + levelVector).WorldToGuiPoint() + new Vector2(-11, -11), new Vector2(23, 22)), "<size=20>x</size>")) { selectedDependencyGroup.subVertices.Remove(vertex); } GUI.contentColor = Color.white; } else { if (GUI.Button(new Rect((vertex.Position + levelVector).WorldToGuiPoint() + new Vector2(-11, -11), new Vector2(23, 22)), "<size=20>+</size>")) { selectedDependencyGroup.subVertices.Add(vertex); } } } } #endregion } } } }
public VocabView(string testStimulus, string correctAns, int displayTimeMillis, int delayTimeMillis, bool mchoice, out IViewResult result) : base() { TextView test = new TextView(testStimulus, displayTimeMillis, GUIUtils.Constants.DISPLAY_FONT_LARGE); //-1 is infinite time if (mchoice) { string[] answers = new string[1]; //Currently the only option is the correct answer //To do: Randomly select a subset of answers OR do free response answers[0] = correctAns; ChoiceView choice = new ChoiceView(answers); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var choicePanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { choicePanel.Enabled = true; rows.Controls.Add(choicePanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(choice, choicePanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { var answer = choice.Result.HasValue ? choice.Result.Value : null; this.SetResult(((string)answer) == correctAns); }); result = this.Result; } else { FreeResponseView frView = new FreeResponseView(); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var frPanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { frPanel.Enabled = true; rows.Controls.Add(frPanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(frView, frPanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { if (frView.Result.HasValue && (string)frView.Result.Value != "") { if (Compute((string)frView.Result.Value, correctAns) < 3) { if ((correctAns == "MONKEY" && (string)frView.Result.Value == "DONKEY") || (correctAns == "DONKEY" && (string)frView.Result.Value == "MONKEY")) { this.SetResult(false); } else if (correctAns == "MANGO" || correctAns == "MAGGOT" || correctAns == "HORSE" || correctAns == "CORPSE") { this.SetResult(Compute((string)frView.Result.Value, correctAns) < 2); } else { this.SetResult(true); } } else { this.SetResult(false); } } else { this.SetResult(false); } }); result = this.Result; } }
private void RenderWindowContents() { if (null == _currentNode) { GUILayout.Label($"Random seed: {PartyParrotManager.Instance.RandomSeed}"); GUILayout.BeginVertical("Rendering:", GUI.skin.box); GUILayout.Label($"Frame Time: {(int)(_lastFrameTime * 1000.0f)} ms"); GUILayout.Label($"Min Frame Time: {(int)(_minFrameTime * 1000.0f)} ms"); GUILayout.Label($"Max Frame Time: {(int)(_maxFrameTime * 1000.0f)} ms"); GUILayout.Label($"Average FPS: {(int)AverageFPS}"); GUILayout.EndVertical(); GUILayout.BeginVertical("Memory:", GUI.skin.box); GUILayout.Label($"Allocated: {Profiler.GetTotalAllocatedMemoryLong() / 1048576.0f:0.00}MB"); GUILayout.Label($"Reserved: {Profiler.GetTotalReservedMemoryLong() / 1048576.0f:0.00}MB"); GUILayout.Label($"Unused: {Profiler.GetTotalUnusedReservedMemoryLong() / 1048576.0f:0.00}MB"); GUILayout.Label($"Mono Heap: {Profiler.GetMonoHeapSizeLong() / 1048576.0f:0.00}MB"); GUILayout.Label($"Mono Used: {Profiler.GetMonoUsedSizeLong() / 1048576.0f:0.00}MB"); GUILayout.EndVertical(); _windowScrollPos = GUILayout.BeginScrollView(_windowScrollPos); foreach (DebugMenuNode node in _nodes) { node.RenderNode(); } GUILayout.EndScrollView(); #if UNITY_EDITOR GUILayout.BeginHorizontal(); if (GUIUtils.LayoutButton("Break")) { Debug.Break(); } _frameStepping = GUILayout.Toggle(_frameStepping, "Enable Frame Stepping (Manually disable in the Hierarchy)"); // TODO: should we force select the manager for the user? GUILayout.EndHorizontal(); #endif GUILayout.BeginHorizontal(); // TODO: reloading doesn't work right /*if(GUIUtils.LayoutButton("Reload")) { * Scenes.SceneManager.Instance.ReloadMainScene(); * }*/ if (GUIUtils.LayoutButton("Quit")) { UnityUtil.Quit(); } if (GUIUtils.LayoutButton("Reset PlayerPrefs")) { PlayerPrefs.DeleteAll(); } GUILayout.EndHorizontal(); } else { _windowScrollPos = GUILayout.BeginScrollView(_windowScrollPos); _currentNode.RenderContents(); GUILayout.EndScrollView(); if (GUIUtils.LayoutButton("Back")) { SetCurrentNode(_currentNode.Parent); } } }
public void ShowSettler(ISettler settler) { if (settler == null) { Debug.LogWarning(typeof(ISettler).Name + " cannot be null!"); M_ScreenManager.SPreviousScreen(); return; } m_settler = settler; settlerName.text = settler.GetName(); settlerUpkeep.text = settler.GetUpkeep().ToString(); settlerMood.value = settler.GetMood(); moodValue.text = string.Format("{0}%", settler.GetMood()); // Preferences List <GameObject> favBuildings = new List <GameObject>(); foreach (FavoriteBuilding favoriteBuilding in settler.GetFavoriteBuildings()) { GameObject obj = Instantiate(favoriteThingRowElementPrefab); if (favoriteBuilding.active) { obj.GetComponent <Image>().color = elemBgHighlightColor; } obj.GetComponentInChildren <TMP_Text>().text = M_BuildingManager.SGetDatBuilding(favoriteBuilding.buildingTemplId).name; obj.GetComponentInChildren <Slider>().value = favoriteBuilding.maxMood; favBuildings.Add(obj); } List <GameObject> favWares = new List <GameObject>(); foreach (FavoriteWare favoriteWare in settler.GetFavoriteWares()) { GameObject obj = Instantiate(favoriteThingRowElementPrefab); if (favoriteWare.active) { obj.GetComponent <Image>().color = elemBgHighlightColor; } obj.GetComponentInChildren <TMP_Text>().text = favoriteWare.ware.ToString(); obj.GetComponentInChildren <Slider>().value = favoriteWare.mood; favWares.Add(obj); } GUIUtils.AddElementsToCleanYScrollContainer(favoriteBuildingsContainer, favBuildings); GUIUtils.AddElementsToCleanYScrollContainer(favoriteWaresContainer, favWares); preferencesSubPage.SetActive(false); settlerPortrait.sprite = M_SettlersManager.SGetPortrait(settler.GetPortraitId()); if (settler.GetWorkplace() != System.Guid.Empty) { workplaceButton.image.sprite = M_BuildingManager.SGetBuilding(settler.GetWorkplace()).GetIcon(); } else { workplaceButton.image.sprite = spriteWhenNoWorkplace; } if (settler.GetHouse() != System.Guid.Empty) { homeButton.image.sprite = M_BuildingManager.SGetBuilding(settler.GetHouse()).GetIcon(); } else { homeButton.image.sprite = spriteWhenNoWorkplace; } M_ScreenManager.SChangeScreenPersistentBack(this.gameObject); }
public void drawInspector() { if (GUIUtils.DrawHeader("Parameters")) { using (new GUIUtils.GUIContents()) { bool isUIEnabled = Recorder.Singleton != null && Recorder.Singleton.State == RecorderState.None; using (new GUIUtils.GUIEnabled(isUIEnabled)) { using (new GUIUtils.GUIContents()) { EditorGUI.BeginChangeCheck(); gifCreatorWindow.Parameters.section = (RecorderParameters.Section)EditorGUILayout.EnumPopup("Screen section", gifCreatorWindow.Parameters.section); if (EditorGUI.EndChangeCheck()) { updateCustomRectPreview(); } EditorGUI.BeginChangeCheck(); { switch (gifCreatorWindow.Parameters.section) { case RecorderParameters.Section.Fullscreen: using (new GUIUtils.GUIEnabled(false)) { EditorGUILayout.IntField("Position X", (int)gifCreatorWindow.Parameters.getRectSection().x); EditorGUILayout.IntField("Position Y", (int)gifCreatorWindow.Parameters.getRectSection().y); EditorGUILayout.IntField("Width", (int)gifCreatorWindow.Parameters.getRectSection().width); EditorGUILayout.IntField("Height", (int)gifCreatorWindow.Parameters.getRectSection().height); } break; case RecorderParameters.Section.CustomRectAbsolute: gifCreatorWindow.Parameters.absolutePosX = EditorGUILayout.IntField("Position X", gifCreatorWindow.Parameters.absolutePosX); gifCreatorWindow.Parameters.absolutePosY = EditorGUILayout.IntField("Position Y", gifCreatorWindow.Parameters.absolutePosY); gifCreatorWindow.Parameters.absoluteWidth = EditorGUILayout.IntField("Width", gifCreatorWindow.Parameters.absoluteWidth); gifCreatorWindow.Parameters.absoluteHeight = EditorGUILayout.IntField("Height", gifCreatorWindow.Parameters.absoluteHeight); if (gifCreatorWindow.Parameters.absolutePosX < 0) { gifCreatorWindow.Parameters.absolutePosX = 0; } if (gifCreatorWindow.Parameters.absolutePosY < 0) { gifCreatorWindow.Parameters.absolutePosY = 0; } if (gifCreatorWindow.Parameters.absoluteWidth + gifCreatorWindow.Parameters.absolutePosX > gifCreatorWindow.Parameters.getMainGameViewSize().x) { gifCreatorWindow.Parameters.absoluteWidth = (int)gifCreatorWindow.Parameters.getMainGameViewSize().x - gifCreatorWindow.Parameters.absolutePosX; } if (gifCreatorWindow.Parameters.absoluteHeight + gifCreatorWindow.Parameters.absolutePosY > gifCreatorWindow.Parameters.getMainGameViewSize().y) { gifCreatorWindow.Parameters.absoluteHeight = (int)gifCreatorWindow.Parameters.getMainGameViewSize().y - gifCreatorWindow.Parameters.absolutePosY; } if (gifCreatorWindow.Parameters.absoluteWidth < 1) { gifCreatorWindow.Parameters.absoluteWidth = 1; } if (gifCreatorWindow.Parameters.absoluteHeight < 1) { gifCreatorWindow.Parameters.absoluteHeight = 1; } if (gifCreatorWindow.Parameters.absolutePosX >= gifCreatorWindow.Parameters.getMainGameViewSize().x) { gifCreatorWindow.Parameters.absolutePosX = (int)gifCreatorWindow.Parameters.getMainGameViewSize().x - 1; } if (gifCreatorWindow.Parameters.absolutePosY >= gifCreatorWindow.Parameters.getMainGameViewSize().y) { gifCreatorWindow.Parameters.absolutePosY = (int)gifCreatorWindow.Parameters.getMainGameViewSize().y - 1; } break; case RecorderParameters.Section.CustomRectRelative: gifCreatorWindow.Parameters.relativePosX = EditorGUILayout.Slider("Position X", gifCreatorWindow.Parameters.relativePosX, 0.0f, 0.99f); gifCreatorWindow.Parameters.relativePosY = EditorGUILayout.Slider("Position Y", gifCreatorWindow.Parameters.relativePosY, 0.0f, 0.99f); gifCreatorWindow.Parameters.relativeWidth = EditorGUILayout.Slider("Width", gifCreatorWindow.Parameters.relativeWidth, 0.01f, 1.0f); gifCreatorWindow.Parameters.relativeHeight = EditorGUILayout.Slider("Height", gifCreatorWindow.Parameters.relativeHeight, 0.01f, 1.0f); if (gifCreatorWindow.Parameters.relativePosX + gifCreatorWindow.Parameters.relativeWidth > 1.0f) { gifCreatorWindow.Parameters.relativeWidth = 1.0f - gifCreatorWindow.Parameters.relativePosX; } if (gifCreatorWindow.Parameters.relativePosY + gifCreatorWindow.Parameters.relativeHeight > 1.0f) { gifCreatorWindow.Parameters.relativeHeight = 1.0f - gifCreatorWindow.Parameters.relativePosY; } break; } switch (gifCreatorWindow.Parameters.section) { case RecorderParameters.Section.CustomRectAbsolute: case RecorderParameters.Section.CustomRectRelative: gifCreatorWindow.Parameters.customRectPreviewColor = EditorGUILayout.ColorField("Custom rect color", gifCreatorWindow.Parameters.customRectPreviewColor); gifCreatorWindow.Parameters.showCustomRectPreview = EditorGUILayout.Toggle("Preview on screen", gifCreatorWindow.Parameters.showCustomRectPreview); break; } } if (EditorGUI.EndChangeCheck()) { updateCustomRectPreview(); } } EditorGUI.BeginChangeCheck(); { gifCreatorWindow.Parameters.framePerSecond = EditorGUILayout.IntSlider(new GUIContent("Frames Per Second", "The number of frames per second the gif will run at."), gifCreatorWindow.Parameters.framePerSecond, 1, 30); gifCreatorWindow.Parameters.duration = EditorGUILayout.Slider(new GUIContent("Duration", "The amount of time (in seconds) to record."), gifCreatorWindow.Parameters.duration, 0.1f, 30f); } if (EditorGUI.EndChangeCheck()) { EditorPrefs.SetInt("gifcreator_fps", gifCreatorWindow.Parameters.framePerSecond); EditorPrefs.SetFloat("gifcreator_duration", gifCreatorWindow.Parameters.duration); } if (gifCreatorWindow.Parameters.repeat < -1) { gifCreatorWindow.Parameters.repeat = -1; } gifCreatorWindow.Parameters.recordWidth = EditorGUILayout.IntField(new GUIContent("Record width", "Even if your screen size is 1280x720 for example. You can specify a different width (640) that will be used to resize each recorded frame. Height is automatically calculated based on the recorded section ratio."), gifCreatorWindow.Parameters.recordWidth); EditorGUILayout.LabelField("Final record dimension", gifCreatorWindow.Parameters.getRecordWidth() + "x" + gifCreatorWindow.Parameters.getRecordHeight()); EditorGUILayout.HelpBox("Estimated memory use: " + gifCreatorWindow.Parameters.getEstimatedMemoryUse().ToString("0") + "MB" + "\n" + gifCreatorWindow.Parameters.getEstimatedMemoryUseDescription(), MessageType.Info); if (gifCreatorWindow.Parameters.recordMode == RecorderParameters.RecordMode.EVERYTHING) { if (gifCreatorWindow.Parameters.getRecordWidth() != gifCreatorWindow.Parameters.getRectSection().width) { EditorGUILayout.HelpBox("Be careful, your record width (" + gifCreatorWindow.Parameters.getRecordWidth() + ") is different than the screen width (" + gifCreatorWindow.Parameters.getRectSection().width + ") you want to record. Gif Creator will resize each recorded frame, each frame, this might result in bad performance and lags during the recording.", MessageType.Warning); } } } } } }
private void BuildView() { this.SuspendLayout(); var tabs = new CustomTabControl() { Dock = DockStyle.Fill }; tabs.DisplayStyleProvider = new TabStyleVisualStudioProvider(tabs) { ShowTabCloser = true }; tabs.TabClosing += (sender, args) => ((CustomTab)args.TabPage).RaiseClosingSafe(args); var startTab = new CustomTab() { Text = "Classifiers " }; // the ending space is necessary for some reason startTab.Closing += (sender, args) => { args.Cancel = true; if (GUIUtils.IsUserSure("Reset classifiers?")) { this.classifierTabs.Clear(); this.Controls.Remove(tabs); tabs.Dispose(); this.BuildView(); this.OnSizeChanged(EventArgs.Empty); } }; // classifier list var classifierList = new CheckedListBox() { Dock = DockStyle.Fill, CheckOnClick = true }; classifierList.AddContextMenu(); Action <ClassificationScheme> addClassifier = (scheme) => { // get unique name if necessary string baseName = string.IsNullOrWhiteSpace(scheme.Settings.Name) ? "new classifier" : scheme.Settings.Name; if (!this.classifierTabs.Select(ct => ct.Text).Contains(baseName)) { scheme.Settings.Name = baseName; } else { int i = 1; while (this.classifierTabs .Select(ct => ct.Text.ToLower()) .Contains(string.Format("{0} {1}", baseName, i))) { i++; } scheme.Settings.Name = string.Format("{0} {1}", baseName, i); } // create the tab var classifierTab = new ClassificationSchemeTab(scheme); classifierTab.TextChanged += (sender, args) => classifierList.Invalidate(); classifierTab.Closing += (sender, args) => { this.classifierTabs.Remove(classifierTab); classifierList.Items.Remove(classifierTab); }; this.classifierTabs.Add(classifierTab); tabs.TabPages.Add(classifierTab); classifierList.Items.Add(classifierTab, true); }; this.getSelectedClassifiers = () => classifierList.CheckedItems.Cast <ClassificationSchemeTab>().Select(cst => cst.ClassificationScheme).ToIArray(); // buttons var buttonTable = GUIUtils.CreateButtonTable(Direction.Horizontal, DockStyle.Bottom, GUIUtils.CreateFlatButton("New", (b) => { var classifier = classifierList.Items.Count > 0 ? ((ClassificationSchemeTab)(classifierList.SelectedItem ?? classifierList.Items[0])).ClassificationScheme : new ClassificationScheme(); classifier.Settings.Name = string.Empty; addClassifier(classifier); }, startTab.ToolTip, "Create a new classifier"), GUIUtils.CreateFlatButton("Load", (b) => { if (this.openDialog.ShowDialog() != DialogResult.OK) { return; } ClassificationScheme scheme; foreach (var path in this.openDialog.FileNames) { if (Utils.TryDeserializeFile(this.openDialog.FileName, out scheme)) { addClassifier(scheme); } else { GUIUtils.Alert("Failed to load classifier info from " + path, MessageBoxIcon.Error); } } }, startTab.ToolTip, "Load a previously saved classifier settings file")); // artifact detection config var artifactDetectionPanel = new ConfigurationPanel(this.artifactDetection); artifactDetectionPanel.PropertyChanged += args => this.artifactDetection.SetProperty(args.Property, args.Getter()); // artifact detection label var artifactDetectionLabel = new Label() { Dock = DockStyle.Bottom, TextAlign = ContentAlignment.MiddleCenter, Visible = false }; IEnumerable <EEGDataEntry> empty = new EEGDataEntry[0], entries = empty; var listener = new EEGDataListener(GUIUtils.GUIInvoker, source => artifactDetectionLabel.Visible = true, data => { if (!this.artifactDetection.UseArtifactDetection) { artifactDetectionLabel.Visible = false; entries = empty; return; } artifactDetectionLabel.Visible = true; entries = entries.Concat(data); if (data.LastItem().TimeStamp - entries.First().TimeStamp >= 500) { if (this.artifactDetection.HasMotionArtifact(entries)) { artifactDetectionLabel.Text = "Motion artifact detected!"; artifactDetectionLabel.BackColor = Color.Red; artifactDetectionLabel.ForeColor = Color.White; if (this.artifactDetection.Beep) { GUIUtils.GUIInvoker.BeginInvoke(SystemSounds.Beep.Play); } } else { artifactDetectionLabel.Text = "No artifacts detected"; artifactDetectionLabel.BackColor = Color.Green; artifactDetectionLabel.ForeColor = Color.Black; } entries = empty; } }, source => artifactDetectionLabel.Visible = false); // avoid using the gui invoker before the handle has been created this.HandleCreated += (sender, args) => EmotivDataSource.Instance.AddListener(listener); artifactDetectionLabel.Disposed += (sender, args) => { EmotivDataSource.Instance.RemoveListener(listener); listener.Dispose(); }; // right half var rightPanel = new Panel() { Dock = DockStyle.Fill }; rightPanel.Controls.Add(classifierList); rightPanel.Controls.Add(buttonTable); // left half var leftPanel = new Panel() { Dock = DockStyle.Fill }; leftPanel.Controls.Add(artifactDetectionPanel); leftPanel.Controls.Add(artifactDetectionLabel); var cols = GUIUtils.CreateTable(new double[] { .5, .5 }, Direction.Horizontal); cols.Controls.Add(rightPanel, 0, 0); cols.Controls.Add(leftPanel, 1, 0); startTab.Controls.Add(cols); tabs.TabPages.Add(startTab); this.Controls.Add(tabs); this.ResumeLayout(false); }
public override Rect GetRect(Rect safeRect, Rect screenRect) { return(GUIUtils.HorizCenterRect(safeRect.center.x, safeRect.yMin + safeRect.height * .1f, 576, 0)); }
private void AeroStressTab(GUIStyle buttonStyle, GUIStyle boxStyle) { int i = 0; int removeIndex = -1; GUILayout.BeginHorizontal(); GUILayout.BeginVertical(boxStyle); for (i = 0; i < FARAeroStress.StressTemplates.Count; i++) { GUILayout.BeginHorizontal(); bool active = GUILayout.Toggle(i == aeroStressIndex, FARAeroStress.StressTemplates[i].name, buttonStyle, GUILayout.Width(150)); if (GUILayout.Button("-", buttonStyle, GUILayout.Width(30), GUILayout.Height(30))) { removeIndex = i; } GUILayout.EndHorizontal(); if (active) { aeroStressIndex = i; } } if (removeIndex >= 0) { FARAeroStress.StressTemplates.RemoveAt(removeIndex); if (aeroStressIndex == removeIndex && removeIndex > 0) { aeroStressIndex--; } removeIndex = -1; } if (GUILayout.Button("+", buttonStyle, GUILayout.Width(30), GUILayout.Height(30))) { FARPartStressTemplate newTemplate = new FARPartStressTemplate(); newTemplate.XZmaxStress = 500; newTemplate.YmaxStress = 500; newTemplate.name = "default"; newTemplate.isSpecialTemplate = false; newTemplate.minNumResources = 0; newTemplate.resources = new List <string>(); newTemplate.excludeResources = new List <string>(); newTemplate.rejectUnlistedResources = false; newTemplate.crewed = false; newTemplate.flowModeNeeded = false; newTemplate.flowMode = ResourceFlowMode.NO_FLOW; FARAeroStress.StressTemplates.Add(newTemplate); } GUILayout.EndVertical(); GUILayout.BeginVertical(boxStyle); FARPartStressTemplate activeTemplate = FARAeroStress.StressTemplates[aeroStressIndex]; string tmp; GUIUtils.TextEntryField("Name:", 80, ref activeTemplate.name); activeTemplate.YmaxStress = GUIUtils.TextEntryForDouble("Axial (Y-axis) Max Stress:", 240, activeTemplate.YmaxStress); activeTemplate.XZmaxStress = GUIUtils.TextEntryForDouble("Lateral (X,Z-axis) Max Stress:", 240, activeTemplate.XZmaxStress); activeTemplate.crewed = GUILayout.Toggle(activeTemplate.crewed, "Requires Crew Compartment"); tmp = activeTemplate.minNumResources.ToString(); GUIUtils.TextEntryField("Min Num Resources:", 80, ref tmp); tmp = Regex.Replace(tmp, @"[^\d]", ""); activeTemplate.minNumResources = Convert.ToInt32(tmp); GUILayout.Label("Req Resources:"); StringListUpdateGUI(activeTemplate.resources, buttonStyle, boxStyle); GUILayout.Label("Exclude Resources:"); StringListUpdateGUI(activeTemplate.excludeResources, buttonStyle, boxStyle); activeTemplate.rejectUnlistedResources = GUILayout.Toggle(activeTemplate.rejectUnlistedResources, "Reject Unlisted Res"); activeTemplate.flowModeNeeded = GUILayout.Toggle(activeTemplate.flowModeNeeded, "Requires Specific Flow Mode"); if (activeTemplate.flowModeNeeded) { activeTemplate.flowMode = (ResourceFlowMode)GUILayout.SelectionGrid((int)activeTemplate.flowMode, FlowMode_str, 1); } activeTemplate.isSpecialTemplate = GUILayout.Toggle(activeTemplate.isSpecialTemplate, "Special Hardcoded Usage"); FARAeroStress.StressTemplates[aeroStressIndex] = activeTemplate; GUILayout.EndVertical(); GUILayout.EndHorizontal(); }
// Update is called once per frame void Update() { if ((wasBothResolved && wasTagged) || (GameState.Singleton.CurrentState != State.Running)) { return; } if (!wasTagged) { foreach (Triple <double, string, string> ct in GameState.Singleton.clickTrace) { if (ct.Second == transform.name) { wasTagged = true; this.click = ct; if (click.Third.Contains("-collab")) { myTag = TagOptions.AssignPartner; } else if (click.Third.Contains("-compete")) { myTag = TagOptions.BlockPartner; } else { myTag = TagOptions.LabelMine; } foreach (Triple <double, string, string> pt in GameState.Singleton.partnerTrace) { // This prevents "future" clicks in the partner trace from firing immediately // by breaking early. if (pt.First >= this.click.First) { break; } if (pt.Second == transform.name) // FOUND IT //Debug.Log("FOUND PARTNER " + transform.name); { switch (myTag) { case TagOptions.LabelMine: if (pt.Third.Contains("-collab")) { GameState.Singleton.score += agreementBonus; string strCollab = "+" + agreementBonus + " points!" + '\n' + "(AGREEMENT)"; GUIUtils.SpawnFloatingText(TagUtils.GetPositionOfChildTag(this.gameObject, click.Third), strCollab, Color.black, 2.0f); Debug.Log(strCollab); } else if (pt.Third.Contains("-compete")) { GameState.Singleton.score -= blockPenalty; string strBlock = "-" + blockPenalty + " points!" + '\n' + "(SELECTED SECOND)"; GUIUtils.SpawnFloatingText(TagUtils.GetPositionOfChildTag(this.gameObject, click.Third), strBlock, Color.black, 2.0f); Debug.Log(strBlock); } break; case TagOptions.AssignPartner: // They agreed with us. GameState.Singleton.score += agreementBonus; string strAgree = "+" + agreementBonus + " points!" + '\n' + "(AGREEMENT)"; GUIUtils.SpawnFloatingText(TagUtils.GetPositionOfChildTag(this.gameObject, click.Third), strAgree, Color.black, 2.0f); Debug.Log(strAgree); break; case TagOptions.BlockPartner: // They beat us to it, so NOTHING HAPPENS :( string strBeaten = "+0 points!" + '\n' + "(SELECTED SECOND)"; GUIUtils.SpawnFloatingText(TagUtils.GetPositionOfChildTag(this.gameObject, click.Third), strBeaten, Color.black, 2.0f); Debug.Log(strBeaten); break; default: break; // WE SHOULD NEVER GET HERE } wasBothResolved = true; } } break; } } } else // wasTagged, but the block hasn't been resolved { foreach (Triple <double, string, string> pt in GameState.Singleton.partnerTrace) { // Skips early traces. if (pt.First < this.click.First) { continue; } // Resolve if we find it (ANDANDNAND) if it's the right time if (pt.Second == transform.name && GameState.Singleton.TimeUsed >= pt.First) // FOUND IT //Debug.Log("FOUND PARTNER " + transform.name); { switch (myTag) { case TagOptions.LabelMine: if (pt.Third.Contains("-collab")) { GameState.Singleton.score += agreementBonus; string strCollab = "+" + agreementBonus + " points!" + '\n' + "(AGREEMENT)"; GUIUtils.SpawnFloatingText(TagUtils.GetPositionOfChildTag(this.gameObject, click.Third), strCollab, Color.black, 2.0f); Debug.Log(strCollab); } else if (pt.Third.Contains("-compete")) { // We beat them to it, but we don't gain/lose anything. Here's where they'd lose points. } break; case TagOptions.AssignPartner: // They agreed with us. GameState.Singleton.score += agreementBonus; string strAgree = "+" + agreementBonus + " points!" + '\n' + "(AGREEMENT)"; GUIUtils.SpawnFloatingText(TagUtils.GetPositionOfChildTag(this.gameObject, click.Third), strAgree, Color.black, 2.0f); Debug.Log(strAgree); break; case TagOptions.BlockPartner: // We beat them. GameState.Singleton.score += blockPenalty; string strBlock = "+" + blockPenalty + " points!" + '\n' + "(SELECTED FIRST)"; GUIUtils.SpawnFloatingText(TagUtils.GetPositionOfChildTag(this.gameObject, click.Third), strBlock, Color.black, 2.0f); Debug.Log(strBlock); break; default: break; // WE SHOULD NEVER GET HERE } wasBothResolved = true; } } } }
// This function is called every editor gui update. In here we are diong our magic to show all to the user in a nice way. public override void OnInspectorGUI() { //Setting styles if (_descBoxStyle == null) { _descBoxStyle = new GUIStyle(GUI.skin.FindStyle("Box")); _descBoxStyle.alignment = TextAnchor.UpperLeft; _descBoxStyle.normal.textColor = Color.white; _descBoxStyle.stretchWidth = true; _bigBoxStyle = new GUIStyle(GUI.skin.FindStyle("Box")); _bigBoxStyle.alignment = TextAnchor.UpperLeft; _bigBoxStyle.normal.textColor = Color.white; _bigBoxStyle.stretchHeight = true; _bigBoxStyle.normal.background = (Texture2D)Resources.Load("SourceBack"); _popupStyle = new GUIStyle(GUI.skin.FindStyle("Popup")); _popupStyle.fontStyle = (FontStyle.Normal); _popupStyle.stretchHeight = true; } EditorGUIUtility.labelWidth = 0; EditorGUIUtility.fieldWidth = 0; serializedObject.Update(); // update the serialized object since the last time this method was called. BaseAction myTarget = (BaseAction)target; myTarget.UpdateInspector(); SerializedProperty script = serializedObject.FindProperty("m_Script"); EditorGUILayout.PropertyField(script, new GUIContent("Script", myTarget.GetActionDescription())); //Show first public visible fields with the Attribute "ShowAtfirst" SerializedProperty prop = serializedObject.GetIterator(); prop.NextVisible(true); do { if (ShouldShowFirst(prop)) { EditorGUILayout.PropertyField(prop, true); } } while (prop.NextVisible(false)); //then show Triggers Rect rect = EditorGUILayout.BeginVertical(); GUI.Box(rect, "", _bigBoxStyle); if (myTarget.IsSupportCustomTriggers()) { GUILayout.Space(5); // Add Trigger row - Combo-box + Add Button Rect addTriggerRect = EditorGUILayout.BeginHorizontal(); { if (_triggerToAdd != null) { // If user pressed on "Add" button - add the selected trigger to the action's supported triggers _supportedTriggers.InsertArrayElementAtIndex(0); _supportedTriggers.GetArrayElementAtIndex(0).objectReferenceValue = myTarget.AddHiddenComponent(_triggerToAdd); ((Trigger)_supportedTriggers.GetArrayElementAtIndex(0).objectReferenceValue).CleanRules(); _triggerToAdd = null; } GUILayout.Box("Add Trigger", _popupStyle); var evt = Event.current; if (evt.type == EventType.mouseDown) { //Getting all Triggers List <System.Type> possibleTriggers = myTarget.GetSupprtedTriggers(); var mousePos = evt.mousePosition; if (addTriggerRect.Contains(mousePos)) { // Now create the menu, add items and show it var menu = new GenericMenu(); for (int i = 0; i < possibleTriggers.Count; i++) { string triggerFriendlyName = ""; if (!_friendlyNames.ContainsKey(possibleTriggers[i].FullName)) { GameObject g = new GameObject("temp"); Trigger triggerTemp = (Trigger)g.AddComponent(possibleTriggers[i]); _friendlyNames.Add(possibleTriggers[i].FullName, triggerTemp.FriendlyName); DestroyImmediate(g); } triggerFriendlyName = _friendlyNames[possibleTriggers[i].FullName]; menu.AddItem(new GUIContent(triggerFriendlyName), false, AddTrigger, possibleTriggers[i]); } menu.ShowAsContext(); evt.Use(); } } } EditorGUILayout.EndHorizontal(); } // go over all the Action's supported triggers and add them to the inspector. for (int i = 0; i < _supportedTriggers.arraySize; i++) { //Get Trigger and update rules Trigger trigger = (Trigger)_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue; if (trigger == null) { ((BaseAction)target).InitializeSupportedTriggers(); EditorGUILayout.EndVertical(); return; } // Trigger Row - Foldout + Reset trigger button + Delete trigger Rect triggerRect = EditorGUILayout.BeginHorizontal(); { trigger.FoldoutOpen = GUIUtils.Foldout(trigger.FoldoutOpen, trigger.FriendlyName); if (trigger.FoldoutOpen) { List <System.Type> supprtedRules1 = trigger.GetSupportedRules(); Rect rectRuleAddButton = EditorGUILayout.BeginHorizontal(); GUILayout.Box("Add", _popupStyle, GUILayout.Width(50)); EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); var evt = Event.current; if (evt.type == EventType.mouseDown) { var mousePos = evt.mousePosition; if (rectRuleAddButton.Contains(mousePos)) { // Now create the menu, add items and show it var menu1 = new GenericMenu(); for (int ri = 0; ri < supprtedRules1.Count(); ri++) { string ruleFriendlyName = ""; if (!_friendlyNames.ContainsKey(supprtedRules1[ri].FullName)) { GameObject g = new GameObject("temp"); BaseRule ruleTemp = (BaseRule)g.AddComponent(supprtedRules1[ri]); _friendlyNames.Add(supprtedRules1[ri].FullName, ruleTemp.FriendlyName); DestroyImmediate(g); } ruleFriendlyName = _friendlyNames[supprtedRules1[ri].FullName]; menu1.AddItem(new GUIContent(ruleFriendlyName), false, AddRule, supprtedRules1[ri]); } menu1.ShowAsContext(); evt.Use(); _triggerToAddRuleTo = trigger; } } } } EditorGUILayout.EndHorizontal(); SetTriggersContextMenu(triggerRect, myTarget, trigger); // show trigger's rules if opened if (trigger.FoldoutOpen) { SerializedObject obj = new SerializedObject(_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue); SerializedProperty rules = obj.FindProperty("Rules"); if (true) { // Add Trigger row - Combo-box + Add Button EditorGUILayout.BeginHorizontal(); { //Adding combo-box control to the inspector with the list of triggers. if (_triggerToAddRuleTo == trigger && _ruleToAdd != null) { // If user pressed on "Add" button - add the selected trigger to the action's supported triggers rules.InsertArrayElementAtIndex(0); rules.GetArrayElementAtIndex(0).objectReferenceValue = myTarget.AddHiddenComponent(_ruleToAdd); // initialize rules _ruleToAdd = null; _triggerToAddRuleTo = null; } } EditorGUILayout.EndHorizontal(); GUILayout.Space(5); } for (int j = 0; j < rules.arraySize; j++) { BaseRule rule = (BaseRule)rules.GetArrayElementAtIndex(j).objectReferenceValue; DrawRuleInspector(rule); //Reset Rule if (_ruleToReset != null && _ruleToReset == rule) { rule.ActionOwner = null; rules.GetArrayElementAtIndex(j).objectReferenceValue = myTarget.AddHiddenComponent(_ruleToReset.GetType()); // Save folded state ((BaseRule)rules.GetArrayElementAtIndex(j).objectReferenceValue).FoldoutOpen = rule.FoldoutOpen; _ruleToReset = null; } //Remove Rule if (_ruleToRemove != null && _ruleToRemove == rule) { // delete the trigger and reorganize the array var r = rules.GetArrayElementAtIndex(j).objectReferenceValue; rules.DeleteArrayElementAtIndex(j); ((BaseRule)r).ActionOwner = null; for (int k = j; k < rules.arraySize - 1; k++) { rules.MoveArrayElement(k + 1, k); } rules.arraySize--; _ruleToRemove = null; } } //Save changes to the rule obj.ApplyModifiedProperties(); } // Reset Trigger if (_triggerToReset != null && _triggerToReset == trigger) { trigger.ActionOwner = null; foreach (BaseRule r in trigger.Rules) { r.ActionOwner = null; } _supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue = myTarget.AddHiddenComponent(trigger.GetType()); Trigger oldTrigger = trigger; trigger = (Trigger)_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue; trigger.CleanRules(); //trigger.SetDefaults(myTarget); myTarget.SetDefaultTriggerValues(i, trigger); // Save folded state trigger.FoldoutOpen = oldTrigger.FoldoutOpen; _triggerToReset = null; break; } // Remove Trigger if (_triggerToRemove != null && _triggerToRemove == trigger) { // delete the trigger and reorganize the array _supportedTriggers.DeleteArrayElementAtIndex(i); trigger.ActionOwner = null; if (trigger.Rules != null) { foreach (BaseRule r in trigger.Rules) { if (r != null) { r.ActionOwner = null; } } } for (int j = i; j < _supportedTriggers.arraySize - 1; j++) { _supportedTriggers.MoveArrayElement(j + 1, j); } _supportedTriggers.arraySize--; break; } } EditorGUILayout.Space(); EditorGUILayout.EndVertical(); // Draw the rest of the control except several predefined fields or the fields which are marked as show first prop = serializedObject.GetIterator(); prop.NextVisible(true); do { if (prop.name != "m_Script" && !ShouldShowFirst(prop)) { EditorGUILayout.PropertyField(prop, true); } } while (prop.NextVisible(false)); //Save changes to the Action Script serializedObject.ApplyModifiedProperties(); }
public static bool ItemTransferValidNew(InventoryItem invitem, UIInventoryGridItem from, UIInventoryGridItem to, out string error, bool alreadyHeld = false) { UIInventoryItemZone owner; error = string.Empty; if (invitem == null || invitem.baseItem == null) { return(true); } if (from == to && UIGlobalInventory.Instance.DragOwnerIsSame()) { return(true); } InventoryItem inventoryItem = invitem; UIInventoryGridItem uIInventoryGridItem = from; if (!to) { owner = null; } else { owner = to.Owner; } if (!UIInventoryGridItem.ItemTransferValid(inventoryItem, uIInventoryGridItem, owner, out error, alreadyHeld)) { return(false); } if (!UIInventoryGridItem.ItemTakeValid(to, out error)) { return(false); } //!+ ADDED CODE // this is to disallow items TO if (IEModOptions.UnlockCombatInv && GameState.InCombat && (to.EquipmentSlot == Equippable.EquipmentSlot.Armor || ForbiddenToMoveItems.Contains(invitem.BaseItem.Name))) { // doesn't allow equipping/unequipping armor during combat, as well as summoned magical items such as druid cat claws error = GUIUtils.GetText(0xd7); return(false); } //!+ END ADD if (to && (to.Locked || to.Blocked || !to.EquipmentModifyValid())) { return(false); } if (to && to.EquipmentSlot != Equippable.EquipmentSlot.None) { error = GUIUtils.GetText(217); Equippable equippable = invitem.baseItem as Equippable; EquipmentSoulbind component = invitem.baseItem.GetComponent <EquipmentSoulbind>(); if (!equippable) { return(false); } if (!equippable.CanUseSlot(to.EquipmentSlot)) { return(false); } if (to.WeaponSetBuddy != null && !to.WeaponSetBuddy.Empty) { if (equippable.BothPrimaryAndSecondarySlot) { error = GUIUtils.GetText(1737); return(false); } Equippable invItem = to.WeaponSetBuddy.InvItem.baseItem as Equippable; if (invItem && invItem.BothPrimaryAndSecondarySlot) { error = GUIUtils.GetText(1737); return(false); } } Equipment selectedEquipment = UIInventoryManager.Instance.Equipment.SelectedEquipment; if (selectedEquipment && selectedEquipment.IsSlotLocked(to.EquipmentSlot)) { return(false); } Equippable.CantEquipReason cantEquipReason = equippable.WhyCantEquip(UIInventoryManager.Instance.SelectedCharacter.gameObject); if (cantEquipReason != Equippable.CantEquipReason.None) { CharacterStats selectedCharacter = UIInventoryManager.Instance.SelectedCharacter; switch (cantEquipReason) { case Equippable.CantEquipReason.EquipmentLocked: { object[] name = new object[] { invitem.baseItem.Name, CharacterStats.Name(selectedCharacter) }; error = GUIUtils.Format(1003, name); break; } case Equippable.CantEquipReason.ClassMismatch: { error = GUIUtils.Format(1003, new object[] { invitem.baseItem.Name, GUIUtils.GetClassString(selectedCharacter.CharacterClass, selectedCharacter.Gender) }); break; } case Equippable.CantEquipReason.SoulboundToOther: { error = GUIUtils.Format(2038, new object[] { equippable.Name, CharacterStats.Name(component.BoundGuid) }); break; } default: { goto case Equippable.CantEquipReason.EquipmentLocked; } } return(false); } } if (from.EquipmentSlot != Equippable.EquipmentSlot.None) { Equipment equipment = UIInventoryManager.Instance.Equipment.SelectedEquipment; if (equipment && to && equipment.IsSlotLocked(to.EquipmentSlot)) { return(false); } } if (to && to.EquipmentSlot == Equippable.EquipmentSlot.Grimoire && UIInventoryManager.Instance.SelectedCharacter.SpellCastingDisabled > 0) { error = GUIUtils.GetText(1738); return(false); } if (to && to.RestrictByFilter != UIInventoryFilter.ItemFilterType.NONE && (invitem.baseItem.FilterType & to.RestrictByFilter) == UIInventoryFilter.ItemFilterType.NONE) { if (to.OrAllowEquipment == Equippable.EquipmentSlot.None || !(invitem.baseItem is Equippable) || !(invitem.baseItem as Equippable).CanUseSlot(to.OrAllowEquipment)) { return(false); } } return(true); }
private void DrawArtsOrders(Rect rect) { CalculateArtValues(); Text.Anchor = TextAnchor.MiddleCenter; Rect buttonRect = new Rect(rect.x + 10, rect.y, rect.width - 20, 25); if (GUIUtils.DrawCustomButton(buttonRect, "RogerEdmonson_OrderWindow_SelectStuff".Translate(artStuff.label), Color.white)) { List <FloatMenuOption> options = new List <FloatMenuOption>(); foreach (var stuff in DefDatabase <ThingDef> .AllDefs) { if (stuff.IsStuff && stuff.stuffProps.CanMake(artType)) { options.Add(new FloatMenuOption(stuff.label, delegate { artStuff = stuff; })); } } Find.WindowStack.Add(new FloatMenu(options)); } buttonRect.y += 30; if (GUIUtils.DrawCustomButton(buttonRect, "RogerEdmonson_OrderWindow_SelectArtType".Translate(artType.label), Color.white)) { List <FloatMenuOption> options = new List <FloatMenuOption>(); foreach (var art in DefDatabase <ThingDef> .AllDefs) { if (art.IsArt) { options.Add(new FloatMenuOption(art.label, delegate { artType = art; })); } } Find.WindowStack.Add(new FloatMenu(options)); } Text.Anchor = TextAnchor.UpperLeft; Rect intRect = new Rect(rect.x + 10, rect.y + 60, 250, 25); Widgets.Label(intRect, "RogerEdmonson_OrderWindow_Range".Translate()); intRect.x += 255; intRect.width = rect.width - 275; Widgets.TextFieldNumeric(intRect, ref delay, ref delayBuff, 1); Rect fullLabel = new Rect(rect.x + 10, rect.y + 90, rect.width - 10, 300); Widgets.Label(fullLabel, "RogerEdmonson_OrderWindow_ArtFull".Translate(totalValue, chance.ToString("f2"), prepayment)); TooltipHandler.TipRegion(fullLabel, "RogerEdmonson_OrderWindow_ArtFull2".Translate(artType.label, baseValue, artStuff.BaseMarketValue, delay, trader.ArriveTime, artType.costStuffCount, totalValue, prepayment , chance.ToString("f2"), baseChance)); Text.Anchor = TextAnchor.MiddleCenter; if (GUIUtils.DrawCustomButton(new Rect(rect.x + 10, rect.height - 40, rect.width - 20, 30), "RogerEdmonson_OrderWindow_CreateOrder".Translate(), trader.Order == null ? Color.white : Color.gray)) { if (trader.Order != null) { Messages.Message("RogerEdmonson_OrderWindow_Only1Order".Translate(), MessageTypeDefOf.NeutralEvent, false); } else { if (TakePrePayment(prepayment)) { MakeArtOrder(chance, totalValue, delay, artType, artStuff); } } } if (trader.Order != null) { if (GUIUtils.DrawCustomButton(new Rect(rect.x + 10, rect.height, rect.width - 20, 30), "DarkNetButtons_CancelOrder".Translate(), Color.white)) { trader.DeclineOrder(); } } Text.Anchor = TextAnchor.UpperLeft; }
public override Rect GetRect(Rect safeRect, Rect screenRect) { return(GUIUtils.CenterRect(safeRect.center.x, safeRect.center.y, 960, safeRect.height * .8f)); }