public void ReverseScriptNameChange(object e) { NameChangedEventArgs eArgs = e as NameChangedEventArgs; if (eArgs == null) { return; } if (ignoreThisNewScriptName == eArgs.NewName) { ignoreThisNewScriptName = null; return; } NWN2GameScript script = eArgs.Item as NWN2GameScript; if (script != null) { Thread.Sleep(1000); try { ignoreThisNewScriptName = eArgs.OldName; script.Name = eArgs.OldName; } catch (Exception) { } } }
/// <summary> /// /// </summary> /// <param name="script"></param> /// <returns></returns> /// <remarks>This method expects that the NWN2GameScript is already Loaded /// (that is, the responsibility for calling Demand() falls to the client.)</remarks> public TriggerControl GetTrigger(NWN2GameScript script) { if (script == null) { throw new ArgumentNullException("script"); } string code, address, naturalLanguage; ScriptWriter.ParseNWScript(script.Data, out code, out address, out naturalLanguage); Nwn2Address nwn2Address = Nwn2Address.TryCreate(address); Nwn2ConversationAddress nwn2ConversationAddress = Nwn2ConversationAddress.TryCreate(address); if (nwn2Address != null) { return(triggerFactory.GetTriggerFromAddress(nwn2Address)); } else if (nwn2ConversationAddress != null) { return(triggerFactory.GetTriggerFromAddress(nwn2ConversationAddress)); } else { throw new ArgumentException("Address must represent a valid Nwn2Address or Nwn2ConversationAddress.", "address"); } }
protected void Watch(NWN2GameScript script) { if (script != null) { script.NameChanged += delegate(object oObject, NameChangedEventArgs eArgs) { OnScriptNameChanged(oObject, eArgs); }; } }
public static bool WasCreatedByFlip(NWN2GameScript script) { if (script == null) { throw new ArgumentNullException("script"); } return(script.Name.StartsWith("flip")); }
public void AddConditionToConversationLine(NWN2ConversationConnector line, NWN2GameConversation conversation) { if (line == null) { throw new ArgumentNullException("line"); } if (conversation == null) { throw new ArgumentNullException("conversation"); } if (!conversation.AllConnectors.Contains(line)) { throw new ArgumentException("Line is not a part of the given conversation.", "line"); } LaunchFlip(); bool openingExistingScript = ScriptHelper.HasFlipScriptAttachedAsCondition(line); if (openingExistingScript && window.AskWhetherToSaveCurrentScript() == MessageBoxResult.Cancel) { return; } window.ConditionalFrame.Address = addressFactory.GetConversationAddress(conversation.Name, line.Line.LineGuid, ScriptType.Conditional).Value; if (openingExistingScript) { NWN2GameScript script = new NWN2GameScript(line.Conditions[0].Script); script.Demand(); FlipScript flipScript = scriptHelper.GetFlipScript(script, Attachment.Ignore); window.OpenFlipScript(new ScriptTriggerTuple(flipScript, null)); window.ConditionalFrame.Dialogue = Nwn2Strings.GetStringFromOEIString(line.Line.Text); //ActivityLog.Write(new Activity("OpenedScript","ScriptName",script.Name,"Event",String.Empty)); Log.WriteAction(LogAction.opened, "script", script.Name + "(attached as condition to line '" + line.Line.Text.GetSafeString(OEIShared.Utils.BWLanguages.CurrentLanguage) + "')"); } else { window.IsDirty = true; window.EnterConditionMode(); window.ConditionalFrame.Dialogue = Nwn2Strings.GetStringFromOEIString(line.Line.Text); //ActivityLog.Write(new Activity("NewScript","CreatedVia","AddingConditionToConversationLine","Event",String.Empty)); string lineText; try { lineText = line.Line.Text.GetSafeString(OEIShared.Utils.BWLanguages.CurrentLanguage).Value; } catch (Exception) { lineText = String.Empty; } Log.WriteAction(LogAction.added, "script", "as condition to a line of conversation ('" + lineText + "')"); } }
public void UseConversationLineAsTrigger(NWN2ConversationConnector line, NWN2GameConversation conversation) { if (line == null) { throw new ArgumentNullException("line"); } if (conversation == null) { throw new ArgumentNullException("conversation"); } if (!conversation.AllConnectors.Contains(line)) { throw new ArgumentException("Line is not a part of the given conversation.", "line"); } LaunchFlip(); window.LeaveConditionMode(); bool openingExistingScript = ScriptHelper.HasFlipScriptAttachedAsAction(line); if (openingExistingScript && window.AskWhetherToSaveCurrentScript() == MessageBoxResult.Cancel) { return; } TriggerControl trigger = triggers.GetTrigger(line, conversation); if (openingExistingScript) { NWN2GameScript script = new NWN2GameScript(line.Actions[0].Script); script.Demand(); FlipScript flipScript = scriptHelper.GetFlipScript(script, Attachment.Ignore); window.OpenFlipScript(new ScriptTriggerTuple(flipScript, trigger)); //ActivityLog.Write(new Activity("OpenedScript","ScriptName",script.Name,"Event",trigger.GetLogText())); Log.WriteAction(LogAction.opened, "script", script.Name + " (attached to line '" + line.Line.Text.GetSafeString(OEIShared.Utils.BWLanguages.CurrentLanguage) + "')"); } else { window.SetTrigger(trigger); window.IsDirty = true; //ActivityLog.Write(new Activity("NewScript","CreatedVia","UsingConversationLineAsEvent","Event",trigger.GetLogText())); string lineText; try { lineText = line.Line.Text.GetSafeString(OEIShared.Utils.BWLanguages.CurrentLanguage).Value; } catch (Exception) { lineText = String.Empty; } Log.WriteAction(LogAction.added, "script", "to a line of conversation ('" + lineText + "')"); } }
public void OpenScript(NWN2GameScript script) { if (script == null) { throw new ArgumentNullException("script"); } LaunchFlip(); if (window.AskWhetherToSaveCurrentScript() == MessageBoxResult.Cancel) { return; } script.Demand(); try { FlipScript flipScript = scriptHelper.GetFlipScript(script, Attachment.Ignore); if (flipScript == null) { throw new InvalidOperationException("Script could not be understood as a Flip script."); } TriggerControl trigger; try { trigger = scriptHelper.GetTrigger(script); } catch (ArgumentException) { trigger = null; } ScriptTriggerTuple tuple = new ScriptTriggerTuple(flipScript, trigger); window.OpenFlipScript(tuple); //ActivityLog.Write(new Activity("OpenedScript","ScriptName",script.Name,"Event",triggerTextForLog)); if (trigger != null) { Log.WriteAction(LogAction.opened, "script", script.Name + " (attached to '" + trigger.GetLogText() + "')"); } else { Log.WriteAction(LogAction.opened, "script", script.Name); } } catch (Exception x) { throw new ApplicationException("Failed to open script '" + script.Name + "'.", x); } }
/// <summary> /// /// </summary> /// <param name="script"></param> /// <returns></returns> /// <remarks>This method expects that the NWN2GameScript is already Loaded /// (that is, the responsibility for calling Demand() falls to the client.)</remarks> public FlipScript GetFlipScript(NWN2GameScript script) { if (script == null) { throw new ArgumentNullException("script"); } string code, address, naturalLanguage; ScriptWriter.ParseNWScript(script.Data, out code, out address, out naturalLanguage); ScriptType scriptType = GetScriptType(script); return(new FlipScript(code, scriptType, script.Name)); }
public static bool HasFlipScriptAttachedAsCondition(NWN2ConversationConnector line) { if (line == null) { throw new ArgumentNullException("line"); } try { if (line.Conditions.Count > 0) { NWN2GameScript script = new NWN2GameScript(line.Conditions[0].Script); return(WasCreatedByFlip(script)); } } catch (Exception) {} return(false); }
/// <summary> /// /// </summary> /// <param name="script"></param> /// <returns></returns> /// <remarks>This method expects that the NWN2GameScript is already Loaded /// (that is, the responsibility for calling Demand() falls to the client.)</remarks> public ScriptType GetScriptType(NWN2GameScript script) { if (script == null) { throw new ArgumentNullException("script"); } if (script.Data.Contains("int StartingConditional()")) { return(ScriptType.Conditional); } else if (script.Data.Contains("void main()")) { return(ScriptType.Standard); } else { throw new ArgumentException("Format of script was not recognised.", "script"); } }
protected void UpdateScriptsFollowingTagChange(object obj, string oldName, string newName, bool createNewCopy) { if (obj == null) { throw new ArgumentNullException("obj"); } if (oldName == null) { throw new ArgumentNullException("oldName"); } if (newName == null) { throw new ArgumentNullException("newName"); } foreach (System.Reflection.PropertyInfo property in obj.GetType().GetProperties()) { if (property.Name.StartsWith("On")) { try { NWN2GameArea area = obj as NWN2GameArea; if (area != null && !session.AreaIsOpen(area)) { area.Demand(); } OEIShared.IO.IResourceEntry res = property.GetValue(obj, null) as OEIShared.IO.IResourceEntry; if (res != null) { NWN2GameScript script = new NWN2GameScript(res); if (ScriptHelper.WasCreatedByFlip(script)) { if (!script.Loaded) { script.Demand(); } string flipCode, address, naturalLanguage; AbstractScriptWriter.ParseNWScript(script.Data, out flipCode, out address, out naturalLanguage); string newAddress = address.Replace(oldName, newName); string newData = script.Data.Replace(address, newAddress); if (createNewCopy) // for instances, create a new copy of the existing script and point at that { NWN2GameScript newScript = session.AddScript(attacher.GetUnusedName(), newData); property.SetValue(obj, newScript.Resource, null); } else // for areas, change the existing script { string n = script.Name; session.DeleteScript(n); NWN2GameScript newScript = session.AddScript(n, newData); property.SetValue(obj, newScript.Resource, null); } } } } catch (Exception x) { MessageBox.Show("Something went wrong when trying to update the scripts on " + newName + ".\n" + x); } } } }
/// <summary> /// Constructs a new <see cref="Sussex.Flip.Games.NeverwinterNightsTwo.Utils.ScriptEventArgs"/> instance. /// </summary> /// <param name="script">The script relating to this event.</param> public ScriptEventArgs(NWN2GameScript script) { this.script = script; }
/// <summary> /// Translates Flip source into NWScript, compiles it, /// and attaches the results to a Neverwinter Nights 2 module. /// </summary> /// <param name="source">The Flip source to be compiled.</param> /// <param name="address">An address representing the location /// to attach this script to.</param> /// <returns>The name the script was saved under.</returns> public override string Attach(FlipScript source, string address) { if (source == null) { throw new ArgumentNullException("source"); } if (address == null) { throw new ArgumentNullException("address"); } if (address == String.Empty) { throw new ArgumentException("Must provide a valid address for attaching script.", "address"); } if (!Nwn2ToolsetFunctions.ToolsetIsOpen()) { throw new InvalidOperationException("Toolset must be open to attach scripts."); } NWN2GameModule module = session.GetModule(); if (module == null) { throw new InvalidOperationException("No module is currently open in the toolset."); } string name = GetUnusedName(); try { if (name.Length > 32) { throw new ApplicationException("Cannot attach script under the generated name ('" + name + "') " + "because it is of length " + name.Length + ", and the maximum " + "valid length of a resource name for NWN2 is 32."); } NWN2GameScript script = session.AddScript(name, source.Code); session.CompileScript(script); if (address.StartsWith("Conversation")) { Nwn2ConversationAddress convAddress = new Nwn2ConversationAddress(address); NWN2GameConversation conversation = session.GetConversation(convAddress.Conversation); if (conversation == null) { throw new ArgumentException("Conversation '" + convAddress.Conversation + "' was not found in current module.", "address"); } // foreach (NWN2Toolset.NWN2.Views.INWN2Viewer v in NWN2Toolset.NWN2ToolsetMainForm.App.GetAllViewers()) { // NWN2Toolset.NWN2.Views.NWN2ConversationViewer cv = v as NWN2Toolset.NWN2.Views.NWN2ConversationViewer; // if (cv != null) { // System.Windows.MessageBox.Show("From viewer...\n" + cv.Conversation.Name + // "\nConnectors: " + cv.Conversation.AllConnectors.Count + "\n" + // "Entries: " + cv.Conversation.Entries.Count + "\n" + // "Replies: " + cv.Conversation.Replies.Count + "\n" + // "Loaded: " + conversation.Loaded); // } // } // // // System.Windows.MessageBox.Show("From module, before insisting on load...\n" + conversation.Name + // "\nConnectors: " + conversation.AllConnectors.Count + "\n" + // "Entries: " + conversation.Entries.Count + "\n" + // "Replies: " + conversation.Replies.Count + "\n" + // "Loaded: " + conversation.Loaded); // // // // if (!conversation.Loaded) conversation.Demand(); // // // System.Windows.MessageBox.Show("From module, after insisting on load...\n" + conversation.Name + // "\nConnectors: " + conversation.AllConnectors.Count + "\n" + // "Entries: " + conversation.Entries.Count + "\n" + // "Replies: " + conversation.Replies.Count + "\n" + // "Loaded: " + conversation.Loaded); NWN2ConversationLine line = session.GetConversationLine(conversation, convAddress.LineID); if (line == null) { throw new ArgumentException("Line with ID " + convAddress.LineID + " was not found in current module.", "address"); } if (convAddress.AttachedAs == ScriptType.Conditional) { session.AttachScriptToConversationAsCondition(script, line, conversation); } else { session.AttachScriptToConversation(script, line, conversation); } } else { Nwn2Address nwn2Address = new Nwn2Address(address); if (!Scripts.IsEventRaiser(nwn2Address.TargetType)) { throw new ArgumentException("Cannot attach scripts to a " + nwn2Address.TargetType + "."); } if (nwn2Address.TargetType == Nwn2Type.Module) { session.AttachScriptToModule(script, nwn2Address.TargetSlot); } else if (nwn2Address.TargetType == Nwn2Type.Area) { NWN2GameArea area = session.GetArea(nwn2Address.AreaTag); if (area == null) { throw new ArgumentException("Area '" + nwn2Address.AreaTag + "' was not found in current module.", "address"); } session.AttachScriptToArea(script, area, nwn2Address.TargetSlot); } else { /* * We want to attach to ALL instances matching the address in ALL OPEN areas, ignoring AreaTag and UseIndex. */ NWN2ObjectType nwn2ObjectType = Nwn2ScriptSlot.GetObjectType(nwn2Address.TargetType).Value; bool attached = false; foreach (NWN2GameArea a in module.Areas.Values) { if (!session.AreaIsOpen(a)) { continue; } NWN2InstanceCollection instances = session.GetObjectsByTag(a, nwn2ObjectType, nwn2Address.InstanceTag); foreach (INWN2Instance instance in instances) { session.AttachScriptToObject(script, instance, nwn2Address.TargetSlot); attached = true; } } /* * We also want to attach to any blueprints which use this tag as their resref. */ // First check that if a blueprint which uses this tag as resref exists, it was created by Narrative Threads: if (nt.CreatedByNarrativeThreads(Nwn2ScriptSlot.GetNwn2Type(nwn2ObjectType), nwn2Address.InstanceTag)) { INWN2Blueprint blueprint = session.GetBlueprint(nwn2Address.InstanceTag.ToLower(), nwn2ObjectType); if (blueprint != null) { session.AttachScriptToBlueprint(script, blueprint, nwn2Address.TargetSlot); attached = true; } } if (!attached) { string error; if (nt.IsLoaded) { error = String.Format("There isn't a {0} with tag '{1}' in any of the areas that are open, or " + "in the blueprints collection.", nwn2Address.TargetType, nwn2Address.InstanceTag); } else { error = String.Format("There isn't a {0} with tag '{1}' in any of the areas that are open.", nwn2Address.TargetType, nwn2Address.InstanceTag); } throw new MatchingInstanceNotFoundException(error, nwn2Address); } } } } catch (MatchingInstanceNotFoundException x) { throw x; } catch (Exception x) { throw new ApplicationException("Something went wrong while saving and attaching script.", x); } if (backups != null) { if (!Directory.Exists(backups)) { try { Directory.CreateDirectory(backups); } catch (Exception) { return(name); } } string saveTo; if (createFoldersForUsers) { try { saveTo = Path.Combine(backups, Environment.UserName); if (!Directory.Exists(saveTo)) { Directory.CreateDirectory(saveTo); } saveTo = Path.Combine(saveTo, module.Name); if (!Directory.Exists(saveTo)) { Directory.CreateDirectory(saveTo); } } catch (Exception) { saveTo = backups; } } else { saveTo = backups; } try { WriteBackup(name, saveTo, source.Code); } catch (Exception) { } } return(name); }
private void condAdvance(Actor trigger, NWN2ScriptVarTable varTable, string questName, int questId, int xp, string script, string message) { LinkedList<String> toRemove = new LinkedList<string>(); toRemove.AddLast("negate"); toRemove.AddLast("condition"); toRemove.AddLast("script"); toRemove.AddLast("message"); varTable = getAdvanceJournalVar(varTable, questName, questId, xp, toRemove); string value = ""; if (preReq == EnumTypes.prereq.SimplePrereq || preReq == EnumTypes.prereq.CastSpecificPrereq) { int questValue = preReqNode.questId; if (questValue == 0) questValue = 1; value = questValue.ToString(); } NWN2GameScript sayString = module.Scripts["gtr_conditional_run_script"]; if (sayString == null) { sayString = new NWN2GameScript("gtr_conditional_run_script", module.Repository.DirectoryName, module.Repository); sayString.Data = Properties.Resources.gtr_conditional_run_script; sayString.OEISerialize(); module.Scripts.Add(sayString); } if (preReq == EnumTypes.prereq.SimplePrereq) { value = "<" + value; NWN2ScriptVariable negate = new NWN2ScriptVariable("negate", 1); varTable.Add(negate); } NWN2ScriptVariable compare1 = new NWN2ScriptVariable("condition", value); NWN2ScriptVariable scriptVar = new NWN2ScriptVariable("script", script); if (message != "") { NWN2ScriptVariable messageVar = new NWN2ScriptVariable("message", message); varTable.Add(messageVar); } varTable.Add(compare1); varTable.Add(scriptVar); trigger.Var = varTable; if (trigger.boolInstance) { ((NWN2TriggerInstance)trigger.instance).OnEnter = sayString.Resource; } else { ((NWN2TriggerBlueprint)trigger.blueprint).OnEnter = sayString.Resource; } }
// // Called when the verify output listview has an item activated. The // item text is parsed to discern whenther the message activated was a // compiler message; if so, an editor window is opened up to the script // namd in the message. // private void OnVerifyOutputListViewItemActivated(object sender, EventArgs e) { ListView OutputListView = (ListView)sender; foreach (object Item in OutputListView.SelectedItems) { INWN2Viewer Viewer; NWN2ScriptViewer ScriptViewer; NWN2GameScript Script; IResourceEntry ResEntry; ListViewItem LvItem = (ListViewItem)Item; string ItemText = LvItem.Text; string ResName; string LineString; string MsgString; int Line; int i; // // Try and parse out the file name and line number of the error // message, if it appears to be a compiler error. // // script1.nss(5): Warning: Usage of switch blocks inside of do/while scopes generates incorrect code with the standard compiler; consider avoiding the use of do/while constructs to ensure correct code generation with the standard compiler i = ItemText.IndexOf('.'); if (i == -1) continue; ResName = ItemText.Substring(0, i); LineString = ItemText.Substring(i+1).ToLower(); if (!LineString.StartsWith("nss(")) continue; i = LineString.IndexOf(')', 4); if (i < 5) continue; MsgString = LineString.Substring(i+1); if (!MsgString.StartsWith(": error: ") && !MsgString.StartsWith(": warning: ")) { continue; } try { Line = Convert.ToInt32(LineString.Substring(4, i - 4)); } catch { continue; } // // Look up the resource in the resource system. // ResEntry = ResourceManager.Instance.GetEntry( new OEIResRef(ResName), (ushort) ResTypes.ResNSS); if (ResEntry is MissingResourceEntry) continue; // // Find the toolset data item for the script in question. // Script = null; try { Viewer = NWN2ToolsetMainForm.App.GetViewerForResource( ResEntry.FullName); if (Viewer != null) Script = (NWN2GameScript)Viewer.ViewedResource; if (Script == null) { Script = NWN2ToolsetMainForm.App.Module.Scripts[ResName]; if (Script == null) { NWN2Campaign Campaign = NWN2CampaignManager.Instance.ActiveCampaign; if (Campaign != null) Script = Campaign.Scripts[ResName]; } if (Script == null) Script = new NWN2GameScript(ResEntry); } } catch { Script = null; } if (Script == null) continue; // // If a viewer isn't open for the script yet, then open one // now. // Viewer = NWN2ToolsetMainForm.App.GetViewerForResource(Script); if (Viewer == null) { NWN2ToolsetMainForm.App.ShowResource(Script); Viewer = NWN2ToolsetMainForm.App.GetViewerForResource(Script); if (Viewer == null) continue; } else { // // Bring the viewer to the front. // NWN2ToolsetMainForm.App.ShowResource(Script); } if (!(Viewer is NWN2ScriptViewer)) continue; ScriptViewer = (NWN2ScriptViewer)Viewer; // // Highlight the error line. // ScriptViewer.HighlightLine(Line); } }
/// <summary> /// If there already exists a conversation by the name in the module, then it is fetched, otherwise a new is created /// </summary> /// <param name="questName">The name of the quset</param> /// <param name="gender">The gender which will be used in the quest</param> /// <param name="lang">The spoken (real world) language</param> /// <returns>The conversation</returns> private NWN2GameConversation conversationFixer(string questName, BWLanguages.Gender gender, BWLanguages.BWLanguage lang) { String convName = String.Empty; NWN2GameConversation cConversation = null; /* If the actor is a creature and does not yet belong to a faction, * I set it to be a commoner. */ #region factionSet if (actor.type == EnumTypes.actorType.Creature) { if (actor.boolInstance) { NWN2CreatureInstance inst = (NWN2CreatureInstance)actor.instance; if (inst.FactionID < 0 || inst.FactionID > 12) { inst.FactionID = 2; } } else { NWN2CreatureBlueprint blue = (NWN2CreatureBlueprint)actor.blueprint; if (blue.FactionID < 0 || blue.FactionID > 12) { blue.FactionID = 2; } } } #endregion #region getConversationName if (actor.Conversation != null && System.IO.Path.GetFileNameWithoutExtension(actor.Conversation.FullName) != String.Empty) { // I get the name of what the conversation is/should be called convName = System.IO.Path.GetFileNameWithoutExtension(actor.Conversation.FullName); } else if (trigger != null) { convName = trigger.ToString() + "Conv"; } else { convName = questNamePrep(questName) + "_" + actor.ToString().Replace(" ", ""); } cConversation = module.Conversations[convName]; #endregion #region ensureConversation // If we still have no conversation, then we create one if (cConversation == null) { cConversation = new NWN2GameConversation(convName, module.Repository.DirectoryName, module.Repository); cConversation.Demand(); } else { cConversation.Demand(); // if we have a conversation, and we have not cleaned it yet - then we do so now, and makes // sure that no one else cleans it if (alreadyWiped[cConversation.Name] == null) { alreadyWiped[cConversation.Name] = true; NWN2ConversationConnectorCollection connectors = cConversation.StartingList; LinkedList<NWN2ConversationConnector> removeList = new LinkedList<NWN2ConversationConnector>(); foreach (NWN2ConversationConnector connnect in connectors) { if (connnect.Comment.Contains("pluginGenerated: " + questName + ":" + questId.ToString())) { removeList.AddLast(connnect); } } debug("Number of convs to remove: " + removeList.Count); foreach (NWN2ConversationConnector removeConnect in removeList) { debug("Removed conversation: " + removeConnect.Text[lang]); cConversation.RemoveNode(removeConnect); } } } cConversation.OEISerialize(true); cConversation.NWN1StyleDialogue = true; #endregion cConversation = constructConv(cConversation, questName, gender, lang); #region FixDoorTalk if (actor.type == EnumTypes.actorType.Placeable || actor.type == EnumTypes.actorType.Door) { NWN2GameScript talkScript = module.Scripts["ga_door_talk"]; if (talkScript == null) { talkScript = new NWN2GameScript("ga_door_talk", module.Repository.DirectoryName, module.Repository); talkScript.Data = Properties.Resources.ga_door_talk; talkScript.OEISerialize(); module.Scripts.Add(talkScript); } actor.doorTalk = talkScript.Resource; } #endregion if (triggerHappens != convType.Explore) actor.Conversation = cConversation.Resource; return cConversation; }
protected void WatchModule(NWN2GameModule mod) { /* Only tracking blueprints which are added to and removed from the module... * this is correct for our purposes! Narrative Threads only uses the module blueprint collections. */ if (mod != null) { /* There seems to be a bug where the following events events fire at a later stage... they do * fire when they should, but when the paused test is allowed to complete, they fire again. */ foreach (NWN2BlueprintCollection bc in mod.BlueprintCollections) { bc.Inserted += delegate(OEICollectionWithEvents cList, int index, object value) { OnBlueprintAdded(bc, new BlueprintEventArgs((INWN2Blueprint)value)); }; bc.Removed += delegate(OEICollectionWithEvents cList, int index, object value) { OnBlueprintRemoved(bc, new BlueprintEventArgs((INWN2Blueprint)value)); }; } List <OEIDictionaryWithEvents> dictionaries; dictionaries = new List <OEIDictionaryWithEvents> { mod.Areas, mod.Conversations, mod.Scripts }; OEIDictionaryWithEvents.ChangeHandler dAdded = new OEIDictionaryWithEvents.ChangeHandler(ResourceInsertedIntoCollection); OEIDictionaryWithEvents.ChangeHandler dRemoved = new OEIDictionaryWithEvents.ChangeHandler(ResourceRemovedFromCollection); foreach (OEIDictionaryWithEvents dictionary in dictionaries) { dictionary.Inserted += dAdded; dictionary.Removed += dRemoved; } // Watch for changes to the names of areas, conversations and scripts: foreach (NWN2GameArea area in mod.Areas) { Watch(area); } foreach (NWN2GameConversation conversation in mod.Conversations) { Watch(conversation); } foreach (NWN2GameScript script in mod.Scripts) { Watch(script); } mod.Areas.Inserted += delegate(OEIDictionaryWithEvents cDictionary, object key, object value) { NWN2GameArea area = value as NWN2GameArea; if (area != null) { Watch(area); } }; mod.Conversations.Inserted += delegate(OEIDictionaryWithEvents cDictionary, object key, object value) { NWN2GameConversation conversation = value as NWN2GameConversation; if (conversation != null) { Watch(conversation); } }; mod.Scripts.Inserted += delegate(OEIDictionaryWithEvents cDictionary, object key, object value) { NWN2GameScript script = value as NWN2GameScript; if (script != null) { Watch(script); } }; } }
private static NWN2GameScript getAdvanceJournal() { NWN2GameScript advanceScript = module.Scripts["ga_advance_journal"]; if (advanceScript == null) { advanceScript = new NWN2GameScript("ga_advance_journal", module.Repository.DirectoryName, module.Repository); advanceScript.Data = Properties.Resources.ga_advance_journal; advanceScript.OEISerialize(); module.Scripts.Add(advanceScript); } return advanceScript; }
/// <summary> /// /// </summary> /// <param name="script"></param> /// <param name="attachment">Only return a script if it is attached /// in the manner indicated by this parameter.</param> /// <returns></returns> /// <remarks>This method expects that the NWN2GameScript is already Loaded /// (that is, the responsibility for calling Demand() falls to the client.)</remarks> public FlipScript GetFlipScript(NWN2GameScript script, Attachment attachment) { if (script == null) { throw new ArgumentNullException("script"); } string code, address, naturalLanguage; ScriptWriter.ParseNWScript(script.Data, out code, out address, out naturalLanguage); ScriptType scriptType = GetScriptType(script); if (attachment == Attachment.Ignore) { return(new FlipScript(code, scriptType, script.Name)); } NWN2GameModule mod = session.GetModule(); if (mod == null) { throw new InvalidOperationException("No module is open."); } Nwn2Address nwn2Address; Nwn2ConversationAddress nwn2ConversationAddress; switch (attachment) { case Attachment.Attached: nwn2Address = Nwn2Address.TryCreate(address); nwn2ConversationAddress = Nwn2ConversationAddress.TryCreate(address); break; case Attachment.AttachedToConversation: nwn2Address = null; nwn2ConversationAddress = Nwn2ConversationAddress.TryCreate(address); break; case Attachment.AttachedToScriptSlot: nwn2Address = Nwn2Address.TryCreate(address); nwn2ConversationAddress = null; break; default: nwn2Address = null; nwn2ConversationAddress = null; break; } if (nwn2Address != null) { try { if (nwn2Address.TargetType == Nwn2Type.Module) { IResourceEntry resource = typeof(NWN2ModuleInformation).GetProperty(nwn2Address.TargetSlot).GetValue(mod.ModuleInfo, null) as IResourceEntry; if (resource != null && resource.ResRef.Value == script.Name) { return(new FlipScript(code, scriptType, script.Name)); } } else if (nwn2Address.TargetType == Nwn2Type.Area) { NWN2GameArea area = session.GetArea(nwn2Address.AreaTag); if (area != null) { IResourceEntry resource = typeof(NWN2GameArea).GetProperty(nwn2Address.TargetSlot).GetValue(area, null) as IResourceEntry; if (resource != null && resource.ResRef.Value == script.Name) { return(new FlipScript(code, scriptType, script.Name)); } } } else { /* * The script might be attached to a Narrative Threads blueprint: */ // First check that if a blueprint which uses this tag as resref exists, it was created by Narrative Threads: if (nt.CreatedByNarrativeThreads(nwn2Address.TargetType, nwn2Address.InstanceTag)) { NWN2ObjectType objectType = Nwn2ScriptSlot.GetObjectType(nwn2Address.TargetType).Value; INWN2Blueprint blueprint = session.GetBlueprint(nwn2Address.InstanceTag.ToLower(), objectType); if (blueprint != null) { IResourceEntry resource = blueprint.GetType().GetProperty(nwn2Address.TargetSlot).GetValue(blueprint, null) as IResourceEntry; if (resource != null && resource.ResRef.Value == script.Name) { return(new FlipScript(code, scriptType, script.Name)); } } } // Check through all OPEN areas. foreach (NWN2GameArea area in mod.Areas.Values) { if (!session.AreaIsOpen(area)) { continue; } NWN2InstanceCollection instances = session.GetObjectsByAddressInArea(nwn2Address, area.Tag); if (instances != null) { // Check the script is still attached to the target object in the slot it claims to be, // in at least one instance, and if so add it to the set of scripts to be opened: foreach (INWN2Instance instance in instances) { IResourceEntry resource = instance.GetType().GetProperty(nwn2Address.TargetSlot).GetValue(instance, null) as IResourceEntry; if (resource != null && resource.ResRef.Value == script.Name) { return(new FlipScript(code, scriptType, script.Name)); } } } } } } catch (Exception x) { throw new ApplicationException(String.Format("Failed to handle script + '{0}' properly.", script.Name), x); } } else if (nwn2ConversationAddress != null) // Check through all conversations, regardless of whether they're open. { NWN2GameConversation conversation = session.GetConversation(nwn2ConversationAddress.Conversation); if (conversation == null) { return(null); } if (NWN2Toolset.NWN2ToolsetMainForm.App.GetViewerForResource(conversation) == null) { conversation.Demand(); } NWN2ConversationLine line = conversation.GetLineFromGUID(nwn2ConversationAddress.LineID); if (line == null) { return(null); } if (line.Actions.Count == 0) { return(null); } IResourceEntry resource = line.Actions[0].Script; if (resource != null && resource.ResRef.Value == script.Name) { return(new FlipScript(code, scriptType, script.Name)); } } return(null); }
// // Called when the verify output listview has an item activated. The // item text is parsed to discern whenther the message activated was a // compiler message; if so, an editor window is opened up to the script // namd in the message. // private void OnVerifyOutputListViewItemActivated(object sender, EventArgs e) { ListView OutputListView = (ListView)sender; foreach (object Item in OutputListView.SelectedItems) { INWN2Viewer Viewer; NWN2ScriptViewer ScriptViewer; NWN2GameScript Script; IResourceEntry ResEntry; ListViewItem LvItem = (ListViewItem)Item; string ItemText = LvItem.Text; string ResName; string LineString; string MsgString; int Line; int i; // // Try and parse out the file name and line number of the error // message, if it appears to be a compiler error. // // script1.nss(5): Warning: Usage of switch blocks inside of do/while scopes generates incorrect code with the standard compiler; consider avoiding the use of do/while constructs to ensure correct code generation with the standard compiler i = ItemText.IndexOf('.'); if (i == -1) { continue; } ResName = ItemText.Substring(0, i); LineString = ItemText.Substring(i + 1).ToLower(); if (!LineString.StartsWith("nss(")) { continue; } i = LineString.IndexOf(')', 4); if (i < 5) { continue; } MsgString = LineString.Substring(i + 1); if (!MsgString.StartsWith(": error: ") && !MsgString.StartsWith(": warning: ")) { continue; } try { Line = Convert.ToInt32(LineString.Substring(4, i - 4)); } catch { continue; } // // Look up the resource in the resource system. // ResEntry = ResourceManager.Instance.GetEntry( new OEIResRef(ResName), (ushort)ResTypes.ResNSS); if (ResEntry is MissingResourceEntry) { continue; } // // Find the toolset data item for the script in question. // Script = null; try { Viewer = NWN2ToolsetMainForm.App.GetViewerForResource( ResEntry.FullName); if (Viewer != null) { Script = (NWN2GameScript)Viewer.ViewedResource; } if (Script == null) { Script = NWN2ToolsetMainForm.App.Module.Scripts[ResName]; if (Script == null) { NWN2Campaign Campaign = NWN2CampaignManager.Instance.ActiveCampaign; if (Campaign != null) { Script = Campaign.Scripts[ResName]; } } if (Script == null) { Script = new NWN2GameScript(ResEntry); } } } catch { Script = null; } if (Script == null) { continue; } // // If a viewer isn't open for the script yet, then open one // now. // Viewer = NWN2ToolsetMainForm.App.GetViewerForResource(Script); if (Viewer == null) { NWN2ToolsetMainForm.App.ShowResource(Script); Viewer = NWN2ToolsetMainForm.App.GetViewerForResource(Script); if (Viewer == null) { continue; } } else { // // Bring the viewer to the front. // NWN2ToolsetMainForm.App.ShowResource(Script); } if (!(Viewer is NWN2ScriptViewer)) { continue; } ScriptViewer = (NWN2ScriptViewer)Viewer; // // Highlight the error line. // ScriptViewer.HighlightLine(Line); } }
/// <summary> /// Fetches the script indicated /// </summary> /// <param name="scriptName">The name of the script that is to be fetched</param> /// <returns>The script</returns> private static IResourceEntry makeScript(string scriptName) { string scriptsPath = Path.Combine(OEIShared.IO.ResourceManager.Instance.BaseDirectory, @"Data\Scripts.zip"); ResourceRepository scripts = (ResourceRepository)OEIShared.IO.ResourceManager.Instance.GetRepositoryByName(scriptsPath); ushort ncs1 = BWResourceTypes.GetResourceType("NSS"); OEIResRef resRef = new OEIResRef(scriptName); IResourceEntry entry = scripts.FindResource(resRef, ncs1); NWN2GameScript script = new NWN2GameScript(entry); script.Demand(); return script.Resource; }