Exemple #1
0
 /// <summary>
 /// Checks whether a given blueprint
 /// appears to have been created by Narrative Threads.
 /// </summary>
 /// <param name="behaviour">The blueprint to check.</param>
 /// <returns>True if the blueprint appears to have
 /// been created by Narrative Threads; false otherwise.</returns>
 public bool CreatedByNarrativeThreads(INWN2Blueprint blueprint)
 {
     if (blueprint == null)
     {
         throw new ArgumentNullException("blueprint");
     }
     return(CreatedByNarrativeThreads(Nwn2ScriptSlot.GetNwn2Type(blueprint.ObjectType), blueprint.Resource.ResRef.Value));
 }
Exemple #2
0
 /// <summary>
 /// Checks whether a given instance
 /// appears to have been created by Narrative Threads.
 /// </summary>
 /// <param name="instance">The instance to check.</param>
 /// <returns>True if the instance appears to have
 /// been created by Narrative Threads; false otherwise.</returns>
 public bool CreatedByNarrativeThreads(INWN2Instance instance)
 {
     if (instance == null)
     {
         throw new ArgumentNullException("instance");
     }
     return(CreatedByNarrativeThreads(Nwn2ScriptSlot.GetNwn2Type(instance.ObjectType), instance.Template.ResRef.Value));
 }
Exemple #3
0
 public InstanceBehaviour(string tag, string displayName, NWN2ObjectType type, string areaTag, string resRef, string iconName) : this(tag, displayName, Nwn2ScriptSlot.GetNwn2Type(type), areaTag, resRef, iconName)
 {
 }
 public BlueprintBehaviour(string resRef, string displayName, string baseResRef, string iconName, NWN2ObjectType type) : this(resRef, displayName, baseResRef, iconName, Nwn2ScriptSlot.GetNwn2Type(type))
 {
 }
        protected void TrackToolsetChanges(ToolsetEventReporter reporter)
        {
            if (!reporter.IsRunning)
            {
                reporter.Start();
            }

            reporter.ModuleChanged += delegate(object oSender, ModuleChangedEventArgs eArgs)
            {
                /* Fires when a module closes, but that doesn't mean that the new module has
                 * been fully opened yet... usually takes a while! */

                Action action = new Action
                                (
                    delegate()
                {
                    if (manager != null)
                    {
                        manager.EmptyBag(AreasBagName);

                        foreach (NWN2ObjectType type in Enum.GetValues(typeof(NWN2ObjectType)))
                        {
                            string bag = String.Format(InstanceBagNamingFormat, type);
                            if (manager.HasBag(bag))
                            {
                                manager.EmptyBag(bag);
                            }
                        }

                        manager.AddMoveable("Creatures", blocks.CreatePlayerBlock());
                    }
                }
                                );

                uiThreadAccess.Dispatcher.Invoke(DispatcherPriority.Normal, action);
            };


            reporter.InstanceAdded += delegate(object sender, InstanceEventArgs e)
            {
                if (manager == null)
                {
                    return;
                }

                string bag = String.Format(InstanceBagNamingFormat, e.Instance.ObjectType.ToString());
                if (!manager.HasBag(bag))
                {
                    return;
                }

                ObjectBlock block = blocks.CreateInstanceBlock(e.Instance, e.Area);
                manager.AddMoveable(bag, block);
            };


            reporter.InstanceRemoved += delegate(object sender, InstanceEventArgs e)
            {
                if (manager == null || e.Instance == null)
                {
                    return;
                }

                string bag = String.Format(InstanceBagNamingFormat, Nwn2ScriptSlot.GetNwn2Type(e.Instance.ObjectType));
                if (!manager.HasBag(bag))
                {
                    return;
                }

                try {
                    UIElementCollection collection = manager.GetMoveables(bag);

                    ObjectBlock lost = blocks.CreateInstanceBlock(e.Instance, e.Area);

                    foreach (ObjectBlock block in collection)
                    {
                        if (block.Equals(lost))
                        {
                            manager.RemoveMoveable(bag, block);
                            return;
                        }
                    }
                }
                catch (Exception) {}
            };


            reporter.BlueprintAdded += delegate(object sender, BlueprintEventArgs e)
            {
                if (manager == null || e.Blueprint == null)
                {
                    return;
                }

                if (nt.CreatedByNarrativeThreads(e.Blueprint))
                {
                    Thread thread = new Thread(new ParameterizedThreadStart(CreateNarrativeThreadsBlock));
                    thread.IsBackground = true;
                    thread.Start(e.Blueprint);
                }

                if (loadBlueprints)
                {
                    Action action = new Action
                                    (
                        delegate()
                    {
                        string bag = String.Format(BlueprintBagNamingFormat, e.Blueprint.ObjectType.ToString());

                        if (manager.HasBag(bag))
                        {
                            ObjectBlock block = blocks.CreateBlueprintBlock(e.Blueprint);
                            manager.AddMoveable(bag, block);
                        }
                    }
                                    );

                    uiThreadAccess.Dispatcher.Invoke(DispatcherPriority.Normal, action);
                }
            };


            reporter.BlueprintRemoved += delegate(object sender, BlueprintEventArgs e)
            {
                if (manager == null || e.Blueprint == null)
                {
                    return;
                }

                if (nt.CreatedByNarrativeThreads(e.Blueprint))
                {
                    Action action = new Action
                                    (
                        delegate()
                    {
                        string bag = String.Format(InstanceBagNamingFormat, e.Blueprint.ObjectType.ToString());

                        if (manager.HasBag(bag))
                        {
                            ObjectBlock lost     = blocks.CreateInstanceBlockFromBlueprint(e.Blueprint);
                            ObjectBlock removing = null;

                            foreach (ObjectBlock block in manager.GetMoveables(bag))
                            {
                                if (block.Equals(lost))
                                {
                                    removing = block;
                                    break;
                                }
                            }

                            if (removing != null)
                            {
                                manager.RemoveMoveable(bag, removing);
                            }
                        }
                    }
                                    );

                    uiThreadAccess.Dispatcher.Invoke(DispatcherPriority.Normal, action);
                }

                if (loadBlueprints)
                {
                    Action action = new Action
                                    (
                        delegate()
                    {
                        string bag = String.Format(BlueprintBagNamingFormat, e.Blueprint.ObjectType.ToString());

                        if (manager.HasBag(bag))
                        {
                            ObjectBlock lost     = blocks.CreateBlueprintBlock(e.Blueprint);
                            ObjectBlock removing = null;

                            foreach (ObjectBlock block in manager.GetMoveables(bag))
                            {
                                if (block.Equals(lost))
                                {
                                    removing = block;
                                    break;
                                }
                            }

                            if (removing != null)
                            {
                                manager.RemoveMoveable(bag, removing);
                            }
                        }
                    }
                                    );

                    uiThreadAccess.Dispatcher.Invoke(DispatcherPriority.Normal, action);
                }
            };


            reporter.AreaOpened += delegate(object sender, AreaEventArgs e)
            {
                if (manager == null)
                {
                    return;
                }

                Thread thread = new Thread(new ParameterizedThreadStart(CreateBlocksWhenAreaIsReady));
                thread.IsBackground = true;
                thread.Start(e.Area);
            };


            reporter.ResourceViewerClosed += delegate(object sender, ResourceViewerClosedEventArgs e)
            {
                if (manager == null)
                {
                    return;
                }

                foreach (Moveable moveable in manager.GetMoveables(AreasBagName))
                {
                    ObjectBlock block = moveable as ObjectBlock;
                    if (block == null)
                    {
                        continue;
                    }
                    AreaBehaviour area = block.Behaviour as AreaBehaviour;
                    if (area == null)
                    {
                        continue;
                    }

                    // Assumes that there are no conversations or scripts with the same name as an
                    // area, but there's no immediately apparent way around this:
                    // (TODO: Could check that module doesn't have a script or conversation of the same name.)
                    if (area.Identifier == e.ResourceName)
                    {
                        manager.RemoveMoveable(AreasBagName, moveable);
                        break;
                    }
                }

                if (NWN2ToolsetMainForm.App.Module != null && NWN2ToolsetMainForm.App.Module.Areas.ContainsCaseInsensitive(e.ResourceName))
                {
                    // At this point we think it's an area that's been closed, so remove
                    // any instances associated with that area:

                    foreach (NWN2ObjectType type in Enum.GetValues(typeof(NWN2ObjectType)))
                    {
                        string bag = String.Format(InstanceBagNamingFormat, type);
                        if (manager.HasBag(bag))
                        {
                            List <Moveable> removing = new List <Moveable>();

                            foreach (Moveable moveable in manager.GetMoveables(bag))
                            {
                                ObjectBlock block = moveable as ObjectBlock;
                                if (block == null)
                                {
                                    continue;
                                }
                                InstanceBehaviour instance = block.Behaviour as InstanceBehaviour;
                                if (instance == null)
                                {
                                    continue;
                                }

                                if (instance.AreaTag.ToLower() == e.ResourceName.ToLower())
                                {
                                    removing.Add(moveable);
                                }
                            }

                            foreach (Moveable moveable in removing)
                            {
                                manager.RemoveMoveable(bag, moveable);
                            }
                        }
                    }
                }
            };


            // Ensure that an area always has the same resource name and tag:
            reporter.AreaNameChanged += delegate(object oObject, NameChangedEventArgs eArgs)
            {
                NWN2GameArea area = eArgs.Item as NWN2GameArea;
                if (area == null)
                {
                    return;
                }

                string blockHasTag = area.Tag;

                if (area.Tag != area.Name)
                {
                    area.Tag = area.Name;
                }
                OEIShared.Utils.OEIExoLocString oeiStr = Nwn2Strings.GetOEIStringFromString(area.Name);
                if (area.DisplayName != oeiStr)
                {
                    area.DisplayName = oeiStr;
                }

                // Note that this will only work for areas that are currently open...
                // we'll deal with changing the name of closed areas when they open.


                // Update the area block, if the area is open:
                bool open = false;
                foreach (NWN2AreaViewer av in NWN2ToolsetMainForm.App.GetAllAreaViewers())
                {
                    if (av.Area == area)
                    {
                        open = true;
                        break;
                    }
                }
                if (!open)
                {
                    return;
                }

                AreaBehaviour behaviour = blocks.CreateAreaBehaviour(area);

                if (manager.HasBag(AreasBagName))
                {
                    UIElementCollection existingBlocks = manager.GetMoveables(AreasBagName);

                    bool updated = false;

                    foreach (UIElement u in existingBlocks)
                    {
                        ObjectBlock existing = u as ObjectBlock;
                        if (existing == null)
                        {
                            continue;
                        }
                        AreaBehaviour existingBehaviour = existing.Behaviour as AreaBehaviour;
                        if (existingBehaviour == null)
                        {
                            continue;
                        }

                        // If you find an area with the same tag, replace its behaviour to update it:
                        if (existingBehaviour.Tag == blockHasTag)
                        {
                            existing.Behaviour = behaviour;
                            updated            = true;
                            break;
                        }
                    }

                    if (!updated)
                    {
                        ObjectBlock block = blocks.CreateAreaBlock(behaviour);
                        manager.AddMoveable(AreasBagName, block, false);
                    }
                }
            };


            // If a script has its name changed, change it back:
            reporter.ScriptNameChanged += delegate(object oObject, NameChangedEventArgs eArgs)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(ReverseScriptNameChange));
                thread.IsBackground = false;
                thread.Start(eArgs);
            };
        }
Exemple #6
0
        /// <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);
        }