コード例 #1
0
ファイル: SubMenus.cs プロジェクト: palmaross/MMSynergy
        public void m_command_Click() // open map
        {
            string aMapGuid      = m_command.ToolTip;
            string _mapName      = m_command.Caption;
            string _mapPlacePath = "";
            string aStorage      = "";
            string _mapLocalPath = "";
            bool   mapnotfound   = true;

            using (MapsDB _db = new MapsDB())
            {
                System.Data.DataTable _dt = _db.ExecuteQuery("select * from MAPS where MAPGUID=`" + aMapGuid + "`");
                if (_dt.Rows.Count != 0)
                {
                    mapnotfound   = false;
                    _mapLocalPath = _dt.Rows[0]["LOCALPATH"].ToString();
                    _mapPlacePath = _dt.Rows[0]["PATHTOPLACE"].ToString();
                    aStorage      = _dt.Rows[0]["STORAGE"].ToString();
                }
            }

            if (mapnotfound)
            {
                System.Windows.Forms.MessageBox.Show(String.Format(MMUtils.GetString("maps.mapnoexists.message"), _mapName),
                                                     MMUtils.GetString("maps.mapnoexists.caption"));
                return; // TODO нужно предложить удалить ее - из БД и из меню
            }

            // if map is opened already
            foreach (Document _map in MMUtils.MindManager.AllDocuments)
            {
                if (SUtils.SynergyMapGuid(_map) == aMapGuid)
                {
                    _map.Activate();
                    return;
                }
            }

            if (Directory.Exists(_mapPlacePath)) // TODO если по причине неподключенного сетевого диска -
            {
                string _latestfile        = Directory.GetFiles(_mapPlacePath, "*.mmap").Last().ToString();
                long   localmap_lastwrite = Convert.ToInt64(File.GetLastWriteTimeUtc(_mapLocalPath).ToString("yyyyMMddHHmmssfff"));
                long   placemap_time      = Convert.ToInt64(Path.GetFileNameWithoutExtension(_latestfile));

                // Check if map in Place is newer than local map, if yes - replace local map
                if (placemap_time > localmap_lastwrite)
                {
                    try
                    {
                        File.Copy(_latestfile, _mapLocalPath, true); // copy (overwrite) map from its Place to local Synergy
                    }
                    catch { } // TODO
                }
            }

            DocumentStorage.reopenmap = false;
            System.IO.File.SetAttributes(_mapLocalPath, System.IO.FileAttributes.Normal);
            MMUtils.MindManager.AllDocuments.Open(_mapLocalPath);
        }
コード例 #2
0
        void m_cmdShareMap_Click()
        {
            string mapGuid = SUtils.SynergyMapGuid(MMUtils.ActiveDocument);

            foreach (Timers item in TIMERS)
            {
                if (item.m_Guid == mapGuid)
                {
                    using (ShareMapDlg _dlg = new ShareMapDlg(MMUtils.ActiveDocument.Name, item.m_PlacePath))
                        _dlg.ShowDialog(new WindowWrapper((IntPtr)MMUtils.MindManager.hWnd));
                    break;
                }
            }
        }
コード例 #3
0
        private void DrawDisabledGuns()
        {
            if (Tick600 || Tick60 && QuickDisableGunsCheck)
            {
                QuickDisableGunsCheck         = false;
                _nearbyGridsTestSphere.Center = CameraPos;
                _gridsNearCamera.Clear();
                _uninitializedBlocks.Clear();

                MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref _nearbyGridsTestSphere, _gridsNearCamera);
                for (int i = _gridsNearCamera.Count - 1; i >= 0; i--)
                {
                    var grid = _gridsNearCamera[i] as MyCubeGrid;
                    if (grid?.Physics != null && !grid.MarkedForClose && !grid.IsPreview && !grid.Physics.IsPhantom)
                    {
                        var fatBlocks = grid.GetFatBlocks();
                        for (int j = 0; j < fatBlocks.Count; j++)
                        {
                            var block = fatBlocks[j];
                            if (block.IsFunctional && WeaponPlatforms.ContainsKey(block.BlockDefinition.Id))
                            {
                                GridAi gridAi;
                                if (!GridTargetingAIs.TryGetValue(block.CubeGrid, out gridAi) || !gridAi.WeaponBase.ContainsKey(block))
                                {
                                    _uninitializedBlocks.Add(block);
                                }
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < _uninitializedBlocks.Count; i++)
            {
                var badBlock = _uninitializedBlocks[i];
                if (badBlock.InScene)
                {
                    var lookSphere = new BoundingSphereD(badBlock.PositionComp.WorldAABB.Center, 30f);
                    if (Camera.IsInFrustum(ref lookSphere))
                    {
                        MyOrientedBoundingBoxD blockBox;
                        SUtils.GetBlockOrientedBoundingBox(badBlock, out blockBox);
                        DsDebugDraw.DrawBox(blockBox, _uninitializedColor);
                    }
                }
            }
        }
コード例 #4
0
        private bool CompRestricted(CoreComponent comp)
        {
            var grid = comp.MyCube?.CubeGrid;

            GridAi ai;

            if (grid == null || !GridTargetingAIs.TryGetValue(grid, out ai))
            {
                return(false);
            }

            MyOrientedBoundingBoxD b;
            BoundingSphereD        s;
            MyOrientedBoundingBoxD blockBox;

            SUtils.GetBlockOrientedBoundingBox(comp.MyCube, out blockBox);

            if (IsWeaponAreaRestricted(comp.MyCube.BlockDefinition.Id.SubtypeId, blockBox, grid, comp.MyCube.EntityId, ai, out b, out s))
            {
                if (!DedicatedServer)
                {
                    if (comp.MyCube.OwnerId == PlayerId)
                    {
                        MyAPIGateway.Utilities.ShowNotification($"Block {comp.MyCube.DisplayNameText} was placed too close to another gun", 10000);
                    }
                }

                if (IsServer)
                {
                    comp.MyCube.CubeGrid.RemoveBlock(comp.MyCube.SlimBlock);
                }
                return(true);
            }

            return(false);
        }
コード例 #5
0
        public static void TopicPortrait(Topic t, string what, string _value, string mapFolderPath)
        {
            int    newline = _value.IndexOf(Environment.NewLine);
            string rootfolder = mapFolderPath;
            string firstline = "", nextline = "";

            if (newline == -1)
            {
                firstline = _value;
            }
            else
            {
                firstline = _value.Substring(0, _value.IndexOf("\r\n"));
                nextline  = _value.Substring(_value.IndexOf("\r\n") + 2);
            }
///TEXT
            if (what == "text")
            {
                t.Text = _value;
            }
            else if (what == "rtf")
            {
                t.Title.TextRTF = _value;
            }
            else if (what == "font")
            {
                string[] _fontvalues = firstline.Split(';');

                t.Text = nextline;

                if (t.TextColor.Value.ToString() != _fontvalues[0])
                {
                    t.TextColor.Value = Convert.ToInt32(_fontvalues[0]);
                }
                if (t.Font.Bold.ToString() != _fontvalues[1])
                {
                    t.Font.Bold = Convert.ToBoolean(_fontvalues[1]);
                }
                if (t.Font.Italic.ToString() != _fontvalues[2])
                {
                    t.Font.Italic = Convert.ToBoolean(_fontvalues[2]);
                }
                if (t.Font.Strikethrough.ToString() != _fontvalues[3])
                {
                    t.Font.Strikethrough = Convert.ToBoolean(_fontvalues[3]);
                }
                if (t.Font.Underline.ToString() != _fontvalues[4])
                {
                    t.Font.Underline = Convert.ToBoolean(_fontvalues[4]);
                }
                if (t.Font.Size.ToString() != _fontvalues[5])
                {
                    t.Font.Size = Convert.ToSingle(_fontvalues[5]);
                }
                if (t.Font.Name != _fontvalues[6])
                {
                    t.Font.Name = _fontvalues[6];
                }
            }
///TASK
            else if (what == "task")
            {
                if (firstline == "empty")
                {
                    if (t.Task.HasEffort)
                    {
                        t.Task.SetEffort(MmDurationUnit.mmDurationUnitDay, 0);
                    }
                    t.Task.Complete  = -1;
                    t.Task.Priority  = MmTaskPriority.mmTaskPriorityNone;
                    t.Task.Resources = "";
                    t.Task.StartDate = MMUtils.NULLDATE;
                    t.Task.DueDate   = MMUtils.NULLDATE;
                    t.Task.Milestone = false;
                }
                else
                {
                    string[] _taskvalues = firstline.Split(';');
                    t.Task.Complete     = Convert.ToInt32(_taskvalues[0]);
                    t.Task.Priority     = MMEnums.Priority(_taskvalues[1]);
                    t.Task.Resources    = _taskvalues[2];
                    t.Task.StartDate    = Convert.ToDateTime(_taskvalues[3]);
                    t.Task.DueDate      = Convert.ToDateTime(_taskvalues[4]);
                    t.Task.DurationUnit = MMEnums.DurationUnit(_taskvalues[5]);
                    t.Task.Milestone    = Convert.ToBoolean(_taskvalues[6]);
                    if (_taskvalues[7] == "0")
                    {
                        if (t.Task.HasEffort)
                        {
                            t.Task.SetEffort(MmDurationUnit.mmDurationUnitDay, 0);
                        }
                    }
                    else
                    {
                        t.Task.EffortUnit = MMEnums.DurationUnit(_taskvalues[7]);
                        t.Task.SetEffort(t.Task.EffortUnit, Convert.ToInt32(_taskvalues[8]));
                    }
                }
            }
///NOTES
            else if (what == "notes")
            {
                string _notesText = firstline;

                if (_notesText == "empty")
                {
                    t.Notes.Text = "";
                }
                else
                {
                    try
                    {
                        t.Notes.TextXHTML = _notesText;
                        t.Notes.Commit();
                    }
                    catch (Exception e)
                    {
                        System.Windows.Forms.MessageBox.Show("Exception: " + e.Message, "Receiving Notes");
                    }
                }
            }
///LINKS
            else if (what == "link")
            {
                foreach (Hyperlink _h in t.Hyperlinks)
                {
                    t.Hyperlinks.Remove(1);
                }

                if (firstline == "empty")
                {
                    return;
                }

                string[] _links;

                if (nextline == "")
                {
                    _links = new string[] { firstline };
                }
                else
                {
                    firstline = firstline + "\r\n" + nextline;
                    nextline  = firstline.Replace("\r", "");
                    _links    = nextline.Split('\n');
                }

                foreach (string _link in _links)
                {
                    string _what  = _link.Substring(0, firstline.IndexOf(":"));
                    string _hlink = _link.Substring(firstline.IndexOf(":") + 1);

                    if (_what == "web" || _what == "file")
                    {
                        t.Hyperlinks.AddHyperlink(_hlink);
                    }
                    else
                    {
                        if (_what == "localtopic")
                        {
                            string _guid = SUtils.FindTopicByAttrGuid(t.Document, _hlink).Guid;
                            t.Hyperlinks.AddHyperlinkToTopicByGuid(_guid);
                        }

                        if (_what == "remotetopic")
                        {
                            string _address = _hlink.Substring(0, _hlink.LastIndexOf(":"));
                            string _guid    = _hlink.Substring(_hlink.LastIndexOf(":") + 1);
                            t.Hyperlinks.AddHyperlinkToTopicByGuid(_guid, _address);
                        }
                    }
                }
            }
///NUMBERING
            else if (what == "numbering")
            {
                string ss        = t.Text;
                string numbering = SUtils.numberinguri;
                //System.Windows.Forms.Clipboard.SetText(t.Xml);
                if (firstline == "empty")
                {
                    t.get_Attributes(numbering).DeleteAll();
                }
                else
                {
                    string   rr      = "";
                    string[] nvalues = firstline.Split(';');
                    if (t.ContainsAttributesNamespace(numbering))
                    {
                        rr = t.get_Attributes(numbering).GetAttributeValue("Depth");
                    }
                    t.get_Attributes(numbering).SetAttributeValue("Depth", nvalues[0].ToString());
                    t.get_Attributes(numbering).SetAttributeValue("Level1Text", nvalues[1].ToString());
                    t.get_Attributes(numbering).SetAttributeValue("Level2Text", nvalues[2].ToString());
                    t.get_Attributes(numbering).SetAttributeValue("Level3Text", nvalues[3].ToString());
                    t.get_Attributes(numbering).SetAttributeValue("Level4Text", nvalues[4].ToString());
                    t.get_Attributes(numbering).SetAttributeValue("Level5Text", nvalues[5].ToString());
                    t.get_Attributes(numbering).SetAttributeValue("Numbering", nvalues[6].ToString());
                    t.get_Attributes(numbering).SetAttributeValue("Separators", nvalues[7].ToString());
                    t.get_Attributes(numbering).SetAttributeValue("Repeat", nvalues[8].ToString());
                }
            }
///IMAGE
            else if (what == "oneimage")
            {
                if (t.HasImage)
                {
                    t.Image.Delete();
                }

                if (firstline != "empty")
                {
                    string[] imgvalues = firstline.Split(';');
                    string   _filename = imgvalues[0];
                    string   _path     = rootfolder + _filename;

                    if (t.HasImage)
                    {
                        t.Image.Load(_path);
                    }
                    else
                    {
                        t.CreateImage(_path);
                    }

                    t.Image.Height = Convert.ToSingle(imgvalues[1]);
                    t.Image.Width  = Convert.ToSingle(imgvalues[2]);
                }
            }
//ICONS
            else if (what == "icons")
            {
                //renove all user icons
                if (t.UserIcons.Count > 0)
                {
                    t.UserIcons.RemoveAll();
                }

                if (firstline == "emptyall")
                {
                    t.Task.Complete = -1;
                    t.Task.Priority = MmTaskPriority.mmTaskPriorityNone;
                }

                if (firstline == "empty" || firstline == "emptyall")
                {
                    return;
                }

                AddIcon(t, firstline, mapFolderPath);

                if (nextline != "")
                {
                    nextline = nextline.Replace("\r", "");
                    string[] _usericons = nextline.Split('\n');

                    foreach (string _iconname in _usericons)
                    {
                        AddIcon(t, _iconname, mapFolderPath);
                    }

                    _usericons = null;
                }
            }

            else if (what == "color")
            {
                string[] _colorvalues = firstline.Split(';');

                if (_colorvalues[0] == "isautomatic")
                {
                    t.FillColor.SetAutomatic();
                }
                else
                {
                    t.FillColor.Value = Convert.ToInt32(_colorvalues[0]);
                }

                if (_colorvalues[1] == "isautomatic")
                {
                    t.LineColor.SetAutomatic();
                }
                else
                {
                    t.LineColor.Value = Convert.ToInt32(_colorvalues[1]);
                }
            }

            else if (what == "subtopicshape")
            {
                if (firstline == "isautomatic")
                {
                    t.Shape.SetAutomatic();
                }
                else
                {
                    string[] _shapevalues = firstline.Split(';');

                    MmStandardTopicShape x = StandardTopicShape(_shapevalues[0]);
                    MmFloatingTopicShape y = FloatingTopicShape(_shapevalues[1]);
                    MmCalloutTopicShape  z = CalloutTopicShape(_shapevalues[1]);

                    t.Shape.SetTypes(x, y, z);
                }
            }
        }
コード例 #6
0
        private void BtnOK_Click(object sender, EventArgs e)
        {
            string _docName     = publishDoc.Name;
            string aPlaceName   = comboMyPlaces.Text;
            string aGuid        = publishDoc.Guid;
            string aLocalPath   = "";
            string aPath        = ""; // full path to published map
            string aSite        = ""; // website to check for Internet connection
            string aProcess     = ""; // cloud app process to check if started
            string _projectName = "";
            string aStorage     = ""; // name of cloud app
            string aProjectPath = "";
            bool   singleMap    = chBoxSingleMap.Checked;

            if (!singleMap)
            {
                _projectName = comboMyProjects.Text;
            }

            // Single Maps
            if (singleMap)
            {
                using (PlacesDB _db = new PlacesDB())
                {
                    DataTable _dt = _db.ExecuteQuery("select * from PLACES where PLACENAME='" + aPlaceName + "'");
                    aProjectPath = _dt.Rows[0]["PLACEPATH"].ToString();
                    aStorage     = _dt.Rows[0]["STORAGE"].ToString();
                    aLocalPath   = MMUtils.m_SynergyLocalPath + aPlaceName + "\\";
                }
            }
            // Projects
            else
            {
                using (ProjectsDB _db = new ProjectsDB())
                {
                    DataTable _dt = _db.ExecuteQuery(
                        "select * from PROJECTS where PROJECTNAME='" + _projectName + "' and PLACENAME='" + aPlaceName + "'");
                    aProjectPath = _dt.Rows[0]["PROJECTPATH"].ToString();
                    aStorage     = _dt.Rows[0]["STORAGE"].ToString();
                    aLocalPath   = MMUtils.m_SynergyLocalPath + aPlaceName + "\\" + _projectName + "\\";
                }
            }

            if (publishDoc.Path == "") // new map not saved yet
            {
                using (NewMapDlg _dlg = new NewMapDlg())
                {
                    if (_dlg.ShowDialog(new WindowWrapper((IntPtr)MMUtils.MindManager.hWnd)) == DialogResult.Cancel)
                    {
                        return;
                    }
                    _docName = _dlg.textBox_MapName.Text + ".mmap";
                }
            }

            aLocalPath = aLocalPath + _docName;

            using (StoragesDB _db = new StoragesDB())
            {
                DataTable _dt = _db.ExecuteQuery("select * from STORAGES where STORAGENAME='" + aStorage + "'");
                aProcess = _dt.Rows[0]["PROCESS"].ToString();
                aSite    = _dt.Rows[0]["SITE"].ToString();
            }

            // Full path to map in Place
            aPath = Path.Combine(aProjectPath, _docName);

            // TODO предложить выбрать сохранение под другим именем
            if (Directory.Exists(aPath)) // map with this name is stored already in this place
            {
                System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show(
                    MMUtils.GetString("publishmapdlg.mapexists.message"),
                    MMUtils.GetString("publishmapdlg.mapexists.caption"),
                    System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
                return;
            }

            string fail = "";

            string messageSite    = MMUtils.GetString("internet.sitefailed.message");
            string messageProcess = MMUtils.GetString("internet.processfailed.message");
            string messagePlace   = MMUtils.GetString("internet.placefail.message");
            string endMessage     = MMUtils.GetString("internet.failed.endpubmessage");

            while ((fail = Internet.CheckInternetAndProcess(aGuid, aStorage, aProcess, aSite, "", "publish")) != "")
            {
                string _message = "", arg = "";

                if (fail == "processfail")
                {
                    _message = messageProcess; arg = aStorage;
                }
                else if (fail == "placefail")
                {
                    _message = messagePlace; arg = aPath;
                }
                else if (fail == "sitefail")
                {
                    _message = messageSite; arg = aSite;
                }

                if (System.Windows.Forms.MessageBox.Show(
                        String.Format(_message, arg) + endMessage,
                        String.Format(MMUtils.GetString("internet.failed.caption"), _docName),
                        System.Windows.Forms.MessageBoxButtons.RetryCancel, System.Windows.Forms.MessageBoxIcon.Exclamation)
                    == System.Windows.Forms.DialogResult.Cancel)
                {
                    this.DialogResult = DialogResult.Cancel;
                    publishDoc        = null;
                    return;
                }

                if (fail == "sitefail")
                {
                    System.Diagnostics.Process.Start(arg); // launch website
                }
            }

            try // Save map to Local
            {
                publishDoc.SaveAs(aLocalPath);
            }
            catch (Exception _e) // TODO cause!!! read-only, etc... имя файла уже исключено выше
            {
                MessageBox.Show("Error: " + _e.Message, "PublishMapDlg", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = DialogResult.Cancel;
                publishDoc        = null;
                return;
            }

            //// Publish Map = set attributes to map, topics, relationships and boundaries and process links ////
            SUtils.singleMap = singleMap;

            Mindjet.MindManager.Interop.Transaction _tr = publishDoc.NewTransaction("");
            _tr.IsUndoable = false;
            _tr.Execute   += new Mindjet.MindManager.Interop.ITransactionEvents_ExecuteEventHandler(SUtils.PublishMap);
            _tr.Start();
            ///////////////////////////////////////////////////////////////////////////////////

            publishDoc.Save();

            if (SUtils.links.Count > 0)
            {
                using (LinkedFilesDlg _dlg = new LinkedFilesDlg(SUtils.links, publishDoc))
                {
                    DialogResult result = _dlg.ShowDialog(new WindowWrapper((IntPtr)MMUtils.MindManager.hWnd));
                    SUtils.links.Clear();
                    if (result == DialogResult.Cancel)
                    {
                        this.DialogResult = DialogResult.Cancel;
                        publishDoc        = null;
                        return;
                    }
                }
            }

            aPath = aPath + "\\"; // Map folder
            string mapFile = SUtils.modtime + ".mmap";

            try // save map to Place
            {
                Directory.CreateDirectory(aPath + "share");
                File.Copy(aLocalPath, aPath + mapFile); // copy as file!!!

                StreamWriter sw = new StreamWriter(File.Create(aPath + "info.ini"));
                sw.WriteLine(aStorage);     // чтобы если нет Интернета или Процесса, выдать сообщение с именем хранилища
                sw.WriteLine(_projectName); // чтобы находить карту из Места в локальной папке Synergy
                sw.WriteLine(aGuid);
                sw.WriteLine(aProcess);     // чтобы проверить Интернет и Процесс
                sw.WriteLine(aSite);        // чтобы проверить Интернет и Процесс
                sw.Close();
            }
            catch (Exception _e) // TODO cause!!! read-only, etc...
            {
                MessageBox.Show(this, "Error " + _e.Message, "title", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = DialogResult.Cancel;
                publishDoc        = null;
                return;
            }

            MapsDB.AddMapToDB(
                aStorage,
                aPlaceName,
                _projectName,
                aGuid, _docName,
                aPath,  // aPath - map directory in Place, with backslash
                aLocalPath,
                DateTime.UtcNow.ToString() + ";" + SUtils.currentUserName + ";" + SUtils.currentUserEmail
                );

            MapsGroup.m_UpdateOpenMap = true; // update Open Map submenu

            SUtils.ProcessMap(publishDoc);

            // Share map
            using (ShareMapDlg _dlg = new ShareMapDlg(MMUtils.ActiveDocument.Name, aPath))
            {
                _dlg.ShowDialog(new WindowWrapper((IntPtr)MMUtils.MindManager.hWnd));
            }

            this.DialogResult = DialogResult.OK;
            publishDoc        = null;
        }
コード例 #7
0
        private void UpdatePlacer()
        {
            if (!Placer.Visible)
            {
                Placer = null;
            }
            if (!MyCubeBuilder.Static.DynamicMode && MyCubeBuilder.Static.HitInfo.HasValue)
            {
                var    hit  = MyCubeBuilder.Static.HitInfo.Value as IHitInfo;
                var    grid = hit.HitEntity as MyCubeGrid;
                GridAi gridAi;
                if (grid != null && GridToMasterAi.TryGetValue(grid, out gridAi))
                {
                    if (MyCubeBuilder.Static.CurrentBlockDefinition != null)
                    {
                        var         subtypeIdHash = MyCubeBuilder.Static.CurrentBlockDefinition.Id.SubtypeId;
                        WeaponCount weaponCount;
                        if (gridAi.WeaponCounter.TryGetValue(subtypeIdHash, out weaponCount))
                        {
                            if (weaponCount.Max > 0 && gridAi.Construct.GetWeaponCount(subtypeIdHash) >= weaponCount.Max)
                            {
                                MyCubeBuilder.Static.NotifyPlacementUnable();
                                MyCubeBuilder.Static.Deactivate();
                                return;
                            }
                        }

                        if (WeaponAreaRestrictions.ContainsKey(subtypeIdHash))
                        {
                            MyOrientedBoundingBoxD restrictedBox;
                            MyOrientedBoundingBoxD buildBox = MyCubeBuilder.Static.GetBuildBoundingBox();
                            BoundingSphereD        restrictedSphere;
                            if (IsWeaponAreaRestricted(subtypeIdHash, buildBox, grid, 0, null, out restrictedBox, out restrictedSphere))
                            {
                                DsDebugDraw.DrawBox(buildBox, _uninitializedColor);
                            }

                            if (MyAPIGateway.Session.Config.HudState == 1)
                            {
                                if (restrictedBox.HalfExtent.AbsMax() > 0)
                                {
                                    DsDebugDraw.DrawBox(restrictedBox, _restrictionAreaColor);
                                }
                                if (restrictedSphere.Radius > 0)
                                {
                                    DsDebugDraw.DrawSphere(restrictedSphere, _restrictionAreaColor);
                                }
                                for (int i = 0; i < gridAi.Weapons.Count; i++)
                                {
                                    MyOrientedBoundingBoxD b;
                                    BoundingSphereD        s;
                                    CoreComponent          Comp = gridAi.Weapons[i];
                                    MyOrientedBoundingBoxD blockBox;
                                    SUtils.GetBlockOrientedBoundingBox(Comp.MyCube, out blockBox);

                                    CalculateRestrictedShapes(Comp.MyCube.BlockDefinition.Id.SubtypeId, blockBox, out b, out s);

                                    if (s.Radius > 0)
                                    {
                                        DsDebugDraw.DrawSphere(s, _restrictionAreaColor);
                                    }
                                    if (b.HalfExtent.AbsMax() > 0)
                                    {
                                        DsDebugDraw.DrawBox(b, _restrictionAreaColor);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #8
0
        private void DrawDisabledGuns()
        {
            if (Tick600 || Tick60 && QuickDisableGunsCheck)
            {
                QuickDisableGunsCheck         = false;
                _nearbyGridsTestSphere.Center = CameraPos;
                _gridsNearCamera.Clear();
                _uninitializedBlocks.Clear();
                _debugBlocks.Clear();

                MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref _nearbyGridsTestSphere, _gridsNearCamera);
                for (int i = _gridsNearCamera.Count - 1; i >= 0; i--)
                {
                    var grid = _gridsNearCamera[i] as MyCubeGrid;
                    if (grid?.Physics != null && !grid.MarkedForClose && !grid.IsPreview && !grid.Physics.IsPhantom)
                    {
                        var fatBlocks = grid.GetFatBlocks();
                        for (int j = 0; j < fatBlocks.Count; j++)
                        {
                            var block = fatBlocks[j];
                            if (block.IsFunctional && WeaponPlatforms.ContainsKey(block.BlockDefinition.Id))
                            {
                                GridAi          gridAi;
                                WeaponComponent comp;
                                if (!GridTargetingAIs.TryGetValue(block.CubeGrid, out gridAi) || !gridAi.WeaponBase.TryGetValue(block, out comp))
                                {
                                    _uninitializedBlocks.Add(block);
                                }
                                else if (comp != null && comp.Data.Repo.Base.Set.Overrides.Debug)
                                {
                                    _debugBlocks.Add(comp);
                                }
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < _uninitializedBlocks.Count; i++)
            {
                var badBlock = _uninitializedBlocks[i];
                if (badBlock.InScene)
                {
                    var lookSphere = new BoundingSphereD(badBlock.PositionComp.WorldAABB.Center, 30f);
                    if (Camera.IsInFrustum(ref lookSphere))
                    {
                        MyOrientedBoundingBoxD blockBox;
                        SUtils.GetBlockOrientedBoundingBox(badBlock, out blockBox);
                        DsDebugDraw.DrawBox(blockBox, _uninitializedColor);
                    }
                }
            }

            for (int i = 0; i < _debugBlocks.Count; i++)
            {
                var comp = _debugBlocks[i];
                if (comp.MyCube.InScene)
                {
                    var lookSphere = new BoundingSphereD(comp.MyCube.PositionComp.WorldAABB.Center, 100f);

                    if (Camera.IsInFrustum(ref lookSphere))
                    {
                        foreach (var w in comp.Platform.Weapons)
                        {
                            if (!w.AiEnabled && w.ActiveAmmoDef.AmmoDef.Trajectory.Guidance == WeaponDefinition.AmmoDef.TrajectoryDef.GuidanceType.Smart)
                            {
                                w.SmartLosDebug();
                            }
                        }
                    }
                }
            }
        }
コード例 #9
0
        void Reopenmaps_Timer_Tick(object sender, EventArgs e)
        {
            reopenmaps_timer.Stop();
            string mapPlacePath = "";

            for (int i = 0; i < _reopenmaps.Count; i++)
            {
                bool   mapnotfound  = true;
                string mapLocalPath = _reopenmaps[i].FullName;

                File.SetAttributes(mapLocalPath, System.IO.FileAttributes.Normal);

                using (MapsDB _db = new MapsDB())
                {
                    DataTable _dt = _db.ExecuteQuery("select * from MAPS where LOCALPATH='" + mapLocalPath + "'");
                    if (_dt.Rows.Count != 0)
                    {
                        mapnotfound  = false;
                        mapPlacePath = _dt.Rows[0]["PATHTOPLACE"].ToString();
                    }
                }

                try
                {
                    mapPlacePath = Directory.GetFiles(mapPlacePath, "*.mmap").Last().ToString();
                }
                catch
                {
                    mapPlacePath = "";
                }

                if (i == _reopenmaps.Count - 1) // last document will be opened, it will be active
                {
                    SUtils.skipActiveMap = false;
                }
                else
                {
                    SUtils.skipActiveMap = true;
                }

                // We have to reopen map to get last map copy from its Place

                if (!mapnotfound && mapPlacePath != "") // map and its placepath found
                {
                    long localmap_lastwrite = Convert.ToInt64(File.GetLastWriteTimeUtc(mapLocalPath).ToString("yyyyMMddHHmmssfff"));
                    long placemap_time      = Convert.ToInt64(Path.GetFileNameWithoutExtension(mapPlacePath));

                    if (placemap_time <= localmap_lastwrite)
                    {
                        string fail = SUtils.ProcessMap(_reopenmaps[i]);

                        if (fail == "")
                        {
                            SUtils.GetChanges(_reopenmaps[i]);
                        }

                        continue;
                    }
                }

                DocumentStorage.closeMap = true;
                _reopenmaps[i].Close();

                // if map or map place not found this will be resolved in the afterOpenMap event
                if (!mapnotfound && mapPlacePath != "")
                {
                    File.Copy(mapPlacePath, mapLocalPath, true); // copy (overwrite) map from its Place to local Synergy
                }
                DocumentStorage.reopenmap = false;
                MMUtils.MindManager.AllDocuments.Open(mapLocalPath);
            }

            _reopenmaps.Clear();
            DestroyTimer();
        }
コード例 #10
0
ファイル: ReceiveChanges.cs プロジェクト: palmaross/MMSynergy
        public static void GetChanges(Document _doc, string _filepath) // _filepath to .txt file in share folder
        {
            //string[] files = Directory.GetFiles(mapFolderPath, "*.txt");

            float  x = 0, y = 0; // callouts, main and floating topics
            int    index  = 1;   // subtopic index in a branch
            string line   = "";
            string _case  = "";
            string _what  = ""; // case details
            string rollup = SUtils.rollupuri;
            //string numbering = SUtils.numberinguri;

            string mapfolderpath = Path.GetDirectoryName(_filepath) + "\\";

            //foreach (string file in files)
            {
                System.IO.StreamReader _file = null;
                try
                {
                    _file = new System.IO.StreamReader(_filepath);
                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show("Exception: " + e.Message, "ReceiveChanges:StreamReader");
                    return;
                }

                line  = _file.ReadLine(); // line 1: case
                _case = line;
                int colon = line.IndexOf(":");

                if (colon != -1)
                {
                    _case = line.Substring(0, colon); // before colon
                    _what = line.Substring(++colon);  // after colon
                    if (!int.TryParse(_what, out index))
                    {
                        index = 1;
                    }
                }

                MapCompanion.received = true; // to repulse event handlers

                switch (_case)
                {
                ///////////////////////// MODIFY TOPIC ///////////////////////
                case "modify":

                    // line 2: topic Guid
                    _t = SUtils.FindTopicByAttrGuid(_doc, _file.ReadLine());
                    if (_t == null)
                    {
                        System.Windows.Forms.MessageBox.Show("ReceiveChanges.CaseModify.TopicNotFound");
                        break;     //TODO
                    }

                    if (_what == "rollup")     // set or remove rollup
                    {
                        if (_t.HasAttributesNamespace[rollup])
                        {
                            _t.IsTaskRollupTopic = false;
                        }
                        else
                        {
                            _t.IsTaskRollupTopic = true;
                        }
                        break;
                    }

                    // line 3: topic text (for chat)
                    forchat = _file.ReadLine();

                    // line 4: timestamp (to attributes)
                    TransactionsWrapper.SetATTR(_t, SUtils.TMODIFIED, _file.ReadLine());

                    // line 5: offset
                    line = _file.ReadLine();
                    if (line != "")
                    {
                        if (_t.IsFloatingTopic || _t.IsMainTopic || _t.IsCalloutTopic)
                        {
                            int w = line.IndexOf(";");
                            float.TryParse(line.Substring(0, w), out x);
                            float.TryParse(line.Substring(w + 1), out y);
                        }
                    }

                    // line 6 to end: value
                    line = _file.ReadLine();
                    string _value = line;

                    while (line != null)
                    {
                        line = _file.ReadLine();
                        if (line != null)
                        {
                            _value = _value + Environment.NewLine + line;
                        }
                    }

                    if (_what != "offset")
                    {
                        PortraitSet.TopicPortrait(_t, _what, _value, mapfolderpath);
                    }

                    if (_t.IsFloatingTopic || _t.IsMainTopic || _t.IsCalloutTopic)
                    {
                        _t.SetOffset(x, y);     //restore topic position
                    }
                    break;
                ////////////////// MODIFY case ends ///////////////////

                /////////////////////////// ADD TOPIC ////////////////////////
                case "add":

                    Topic        _parent  = null;
                    Boundary     _bparent = null;
                    Relationship _rparent = null;

                    // line 2: parent guid
                    line = _file.ReadLine();
                    if (line != "")     // empty if floating topic
                    {
                        if (_what == "relcallout")
                        {
                            _rparent = SUtils.FindRelationshipByAttrGuid(_doc, line);
                        }
                        else if (_what == "bndcallout")
                        {
                            _bparent = SUtils.FindBoundaryByAttrGuid(_doc, line);
                        }
                        else
                        {
                            _parent = SUtils.FindTopicByAttrGuid(_doc, line);
                        }
                        if (_parent == null && _rparent == null && _bparent == null)
                        {
                            System.Windows.Forms.MessageBox.Show("ReceiveChanges.CaseAdd.ObjectNotFound");
                            break;     // TODO обнаружить ошибку - сообщить пользователю?
                        }
                    }

                    // line 3: topic text - for chat
                    forchat = _file.ReadLine();

                    // line 4: added topic guid : add topic
                    line = _file.ReadLine();
                    if (_what == "floating")
                    {
                        _t = _doc.AllFloatingTopics.Add();
                    }
                    else if (_what == "callout")
                    {
                        _t = _parent.AllCalloutTopics.Add();
                    }
                    else if (_what == "relcallout")
                    {
                        _t = _rparent.AllCalloutTopics.Add();
                    }
                    else if (_what == "bndcallout")
                    {
                        _t = _bparent.CreateSummaryTopic(MMUtils.GetString("callout.text"));
                    }
                    else
                    {
                        _t = _parent.AllSubTopics.Add();
                        _parent.AllSubTopics.Insert(_t, index); // EventDocumentClipboardPaste fires!
                        MapCompanion.paste = false;             // so, neutralize it...
                    }

                    TransactionsWrapper.SetATTR(_t, SUtils.OGUID, line);

                    // line 5: timestamp
                    line = _file.ReadLine();
                    TransactionsWrapper.SetATTR(_t, SUtils.TADDED, line);
                    TransactionsWrapper.SetATTR(_t, SUtils.TMODIFIED, line);

                    // line 6: offset
                    line = _file.ReadLine();
                    if (line != "")     // skip standart topics
                    {
                        int w = line.IndexOf(";");
                        float.TryParse(line.Substring(0, w), out x);
                        float.TryParse(line.Substring(w + 1), out y);
                    }
                    if (_t.IsFloatingTopic || _t.IsMainTopic || _t.IsCalloutTopic)
                    {
                        _t.SetOffset(x, y);
                    }

                    // line 7: skip if new topic added, otherwise (topic was pasted) replace whole topic xml
                    line = _file.ReadLine();     // <?xml version="1.0" standalone="no"?>
                    if (line != "newtopic")
                    {
                        _t.Xml = line + _file.ReadLine();     // topic XML
                        if (_t.IsFloatingTopic || _t.IsMainTopic || _t.IsCalloutTopic)
                        {
                            _t.SetOffset(x, y);
                        }
                    }

                    _parent = null; _rparent = null; _bparent = null;
                    break;
                ///////////////////// ADD TOPIC case ends ////////////////////////

                //////////// DELETE TOPIC OR RELATIONSHIP OR BOUNDARY ////////////
                case "delete":

                    // line 2: guid of object to delete
                    line = _file.ReadLine();

                    DocumentObject m_objtodelete = null;
                    m_objtodelete = SUtils.FindObjectByAttrGuid(_doc, line);

                    if (m_objtodelete == null)
                    {
                        System.Windows.Forms.MessageBox.Show("ReceiveChanges.CaseDelete.ObjectNotFound");
                        break;     // TODO map synchro failure, do something
                    }

                    m_objtodelete.Delete();
                    m_objtodelete = null;

                    // line 3: for chat: topic text or "relationship" or "boundary"
                    forchat = _file.ReadLine();

                    // line 4: for chat: name of user who deleted object
                    username = _file.ReadLine();

                    break;
                //////////////////// DELETE case ends ////////////////////

                //////////////////// RELATIONSHIP ADD, MODIFY //////////////////
                case "relationship":
                    Relationship rel = null;

                    // line 2: relationship guid
                    line = _file.ReadLine();
                    if (_what == "modify")
                    {
                        rel = SUtils.FindRelationshipByAttrGuid(_doc, line);
                        if (rel == null)
                        {
                            System.Windows.Forms.MessageBox.Show("ReceiveChanges.CaseRelationships.RelNotFound");
                            break;
                        }
                    }

                    // line 3: Guid of connection 1st object
                    string Guid1 = _file.ReadLine();
                    Topic  t1 = null, t2 = null;

                    Boundary b1 = SUtils.FindBoundaryByAttrGuid(_doc, Guid1);
                    if (b1 == null)
                    {
                        t1 = SUtils.FindTopicByAttrGuid(_doc, Guid1);
                    }

                    if (b1 == null && t1 == null)
                    {
                        System.Windows.Forms.MessageBox.Show("ReceiveChanges.CaseRelationships.Object1NotFound");
                        break;     // TODO
                    }

                    // line 4:
                    string Guid2 = _file.ReadLine();

                    Boundary b2 = SUtils.FindBoundaryByAttrGuid(_doc, Guid2);
                    if (b2 == null)
                    {
                        t2 = SUtils.FindTopicByAttrGuid(_doc, Guid2);
                    }

                    if (b2 == null && t2 == null)
                    {
                        System.Windows.Forms.MessageBox.Show("ReceiveChanges.CaseRelationships.Object2NotFound");
                        break;     // TODO
                    }

                    if (b1 == null)
                    {
                        if (b2 == null)
                        {
                            if (_what == "modify")
                            {
                                rel.SetConnection1ToTopic(t1);
                                rel.SetConnection2ToTopic(t2);
                            }
                            else
                            {
                                rel = t1.AllRelationships.AddToTopic(t2);
                                TransactionsWrapper.SetAttributes(rel, line);
                            }
                        }
                        else
                        if (_what == "modify")
                        {
                            rel.SetConnection1ToTopic(t1);
                            rel.SetConnection2ToBoundary(b2);
                        }
                        else
                        {
                            rel = t1.AllRelationships.AddToBoundary(b2);
                            TransactionsWrapper.SetAttributes(rel, line);
                        }
                    }
                    else
                    {
                        if (b2 == null)
                        {
                            if (_what == "modify")
                            {
                                rel.SetConnection1ToBoundary(b1);
                                rel.SetConnection2ToTopic(t2);
                            }
                            else
                            {
                                rel = b1.AllRelationships.AddToTopic(t2);
                                TransactionsWrapper.SetAttributes(rel, line);
                            }
                        }
                        else
                        if (_what == "modify")
                        {
                            rel.SetConnection1ToBoundary(b1);
                            rel.SetConnection2ToBoundary(b2);
                        }
                        else
                        {
                            rel = b1.AllRelationships.AddToBoundary(b2);
                            TransactionsWrapper.SetAttributes(rel, line);
                        }
                    }

                    // line 5-8: control points
                    if ((line = _file.ReadLine()) == null)     //new rel added, go out
                    {
                        break;
                    }
                    rel.SetControlPoints(
                        Convert.ToSingle(line),
                        Convert.ToSingle(_file.ReadLine()),
                        Convert.ToSingle(_file.ReadLine()),
                        Convert.ToSingle(_file.ReadLine())
                        );

                    // line 9-10:

                    rel.Shape1 = RelationshipShape(_file.ReadLine());
                    rel.Shape2 = RelationshipShape(_file.ReadLine());

                    // line 11:
                    rel.LineColor.Value = Convert.ToInt32(_file.ReadLine());

                    // line 12:
                    rel.LineDashStyle = LineDashStyle(_file.ReadLine());

                    // line 13:
                    rel.LineShape = LineShape(_file.ReadLine());

                    // line 14:
                    rel.LineWidth = Convert.ToSingle(_file.ReadLine());

                    // line 15:
                    rel.AutoRouting = Convert.ToBoolean(_file.ReadLine());

                    rel = null; t1 = null; t2 = null; b1 = null; b2 = null;

                    break;
                /////////////// RELATIONSHIP case ends //////////

                /////////////////// ADD OR MODIFY BOUNDARY ////////////////
                case "boundary":
                    // line 2: topic guid
                    _t = SUtils.FindTopicByAttrGuid(_doc, _file.ReadLine());
                    Boundary b = null;

                    // line 3: boundary shape or portrait
                    if (_what == "add")
                    {
                        b       = _t.CreateBoundary();
                        b.Shape = BoundaryShape(_file.ReadLine());
                    }
                    else     // modify boundary
                    {
                        b = _t.Boundary;
                        string[] bvalues = _file.ReadLine().Split(';');

                        b.Shape           = MMEnums.BoundaryShape(bvalues[0]);
                        b.FillColor.Value = Convert.ToInt32(bvalues[1]);
                        b.LineColor.Value = Convert.ToInt32(bvalues[2]);
                        b.LineDashStyle   = MMEnums.LineDashStyle(bvalues[3]);
                        b.LineWidth       = Convert.ToInt32(bvalues[4]);
                    }

                    // line 4: boundary guid
                    TransactionsWrapper.SetAttributes(b, _file.ReadLine());

                    b = null;
                    break;
                    ////////////// BOUNDARY case ends ////////////////
                }

                MapCompanion.received = false;
                _file.Close();
                _t = null; // TODO dooble-check! very important!!
                //File.Delete(file);
            } // foreach files

            //MMBase.SendMessage("received"); // TODO nedeed?
        }
コード例 #11
0
        private void DamageGrid(HitEntity hitEnt, ProInfo t)
        {
            var grid = hitEnt.Entity as MyCubeGrid;

            if (grid == null || grid.MarkedForClose || !hitEnt.HitPos.HasValue || hitEnt.Blocks == null)
            {
                hitEnt.Blocks?.Clear();
                return;
            }
            if (t.AmmoDef.DamageScales.Shields.Type == ShieldDef.ShieldType.Heal || (!t.AmmoDef.Const.SelfDamage || !MyAPIGateway.Session.SessionSettings.EnableTurretsFriendlyFire) && t.Ai.MyGrid.IsSameConstructAs(grid))
            {
                t.BaseDamagePool = 0;
                return;
            }

            _destroyedSlims.Clear();
            _destroyedSlimsClient.Clear();
            var largeGrid      = grid.GridSizeEnum == MyCubeSize.Large;
            var areaRadius     = largeGrid ? t.AmmoDef.Const.AreaRadiusLarge : t.AmmoDef.Const.AreaRadiusSmall;
            var detonateRadius = largeGrid ? t.AmmoDef.Const.DetonateRadiusLarge : t.AmmoDef.Const.DetonateRadiusSmall;
            var maxObjects     = t.AmmoDef.Const.MaxObjectsHit;
            var areaEffect     = t.AmmoDef.AreaEffect.AreaEffect;
            var explosive      = areaEffect == AreaEffectType.Explosive;
            var radiant        = areaEffect == AreaEffectType.Radiant;
            var detonateOnEnd  = t.AmmoDef.AreaEffect.Detonation.DetonateOnEnd;
            var detonateDmg    = t.DetonationDamage;
            var shieldBypass   = t.AmmoDef.DamageScales.Shields.Type == ShieldDef.ShieldType.Bypass;
            var attackerId     = shieldBypass ? grid.EntityId : t.Target.FiringCube.EntityId;
            var attacker       = shieldBypass ? (MyEntity)grid : t.Target.FiringCube;
            var areaEffectDmg  = areaEffect != AreaEffectType.Disabled ? t.AreaEffectDamage : 0;
            var hitMass        = t.AmmoDef.Mass;
            var sync           = MpActive && (DedicatedServer || IsServer);
            var hasAreaDmg     = areaEffectDmg > 0;
            var radiantCascade = radiant && !detonateOnEnd;
            var primeDamage    = !radiantCascade || !hasAreaDmg;
            var radiantBomb    = radiant && detonateOnEnd;
            var damageType     = explosive || radiant ? MyDamageType.Explosion : MyDamageType.Bullet;

            var fallOff          = t.AmmoDef.Const.FallOffScaling && t.DistanceTraveled > t.AmmoDef.DamageScales.FallOff.Distance;
            var fallOffMultipler = 1f;

            if (fallOff)
            {
                fallOffMultipler = (float)MathHelperD.Clamp(1.0 - ((t.DistanceTraveled - t.AmmoDef.DamageScales.FallOff.Distance) / (t.AmmoDef.Const.MaxTrajectory - t.AmmoDef.DamageScales.FallOff.Distance)), t.AmmoDef.DamageScales.FallOff.MinMultipler, 1);
            }

            var damagePool = t.BaseDamagePool;

            if (t.AmmoDef.Const.VirtualBeams)
            {
                var hits = t.WeaponCache.Hits;
                damagePool    *= hits;
                areaEffectDmg *= hits;
            }
            var objectsHit           = t.ObjectsHit;
            var countBlocksAsObjects = t.AmmoDef.ObjectsHit.CountBlocks;

            List <Vector3I> radiatedBlocks = null;

            if (radiant)
            {
                GetBlockSphereDb(grid, areaRadius, out radiatedBlocks);
            }

            var done     = false;
            var nova     = false;
            var outOfPew = false;

            for (int i = 0; i < hitEnt.Blocks.Count; i++)
            {
                if (done || outOfPew && !nova)
                {
                    break;
                }

                var rootBlock = hitEnt.Blocks[i];

                if (!nova)
                {
                    if (_destroyedSlims.Contains(rootBlock) || _destroyedSlimsClient.Contains(rootBlock))
                    {
                        continue;
                    }
                    if (rootBlock.IsDestroyed)
                    {
                        _destroyedSlims.Add(rootBlock);
                        if (IsClient)
                        {
                            _destroyedSlimsClient.Add(rootBlock);
                            if (_slimHealthClient.ContainsKey(rootBlock))
                            {
                                _slimHealthClient.Remove(rootBlock);
                            }
                        }
                        continue;
                    }
                }
                var door = rootBlock.FatBlock as MyDoorBase;
                if (door != null && door.Open && !HitDoor(hitEnt, door))
                {
                    continue;
                }

                var radiate  = radiantCascade || nova;
                var dmgCount = 1;
                if (radiate)
                {
                    if (nova)
                    {
                        GetBlockSphereDb(grid, detonateRadius, out radiatedBlocks);
                    }
                    if (radiatedBlocks != null)
                    {
                        ShiftAndPruneBlockSphere(grid, rootBlock.Position, radiatedBlocks, _slimsSortedList);
                    }

                    done     = nova;
                    dmgCount = _slimsSortedList.Count;
                }

                for (int j = 0; j < dmgCount; j++)
                {
                    var   block       = radiate ? _slimsSortedList[j].Slim : rootBlock;
                    var   blockHp     = !IsClient ? block.Integrity : _slimHealthClient.ContainsKey(block) ? _slimHealthClient[block] : block.Integrity;
                    float damageScale = 1;

                    if (t.AmmoDef.Const.DamageScaling)
                    {
                        var d = t.AmmoDef.DamageScales;
                        if (d.MaxIntegrity > 0 && blockHp > d.MaxIntegrity)
                        {
                            outOfPew   = true;
                            damagePool = 0;
                            continue;
                        }

                        if (d.Grids.Large >= 0 && largeGrid)
                        {
                            damageScale *= d.Grids.Large;
                        }
                        else if (d.Grids.Small >= 0 && !largeGrid)
                        {
                            damageScale *= d.Grids.Small;
                        }

                        MyDefinitionBase blockDef = null;
                        if (t.AmmoDef.Const.ArmorScaling)
                        {
                            blockDef = block.BlockDefinition;
                            var isArmor = AllArmorBaseDefinitions.Contains(blockDef);
                            if (isArmor && d.Armor.Armor >= 0)
                            {
                                damageScale *= d.Armor.Armor;
                            }
                            else if (!isArmor && d.Armor.NonArmor >= 0)
                            {
                                damageScale *= d.Armor.NonArmor;
                            }

                            if (isArmor && (d.Armor.Light >= 0 || d.Armor.Heavy >= 0))
                            {
                                var isHeavy = HeavyArmorBaseDefinitions.Contains(blockDef);
                                if (isHeavy && d.Armor.Heavy >= 0)
                                {
                                    damageScale *= d.Armor.Heavy;
                                }
                                else if (!isHeavy && d.Armor.Light >= 0)
                                {
                                    damageScale *= d.Armor.Light;
                                }
                            }
                        }
                        if (t.AmmoDef.Const.CustomDamageScales)
                        {
                            if (blockDef == null)
                            {
                                blockDef = block.BlockDefinition;
                            }
                            float modifier;
                            var   found = t.AmmoDef.Const.CustomBlockDefinitionBasesToScales.TryGetValue(blockDef, out modifier);

                            if (found)
                            {
                                damageScale *= modifier;
                            }
                            else if (t.AmmoDef.DamageScales.Custom.IgnoreAllOthers)
                            {
                                continue;
                            }
                        }
                        if (fallOff)
                        {
                            damageScale *= fallOffMultipler;
                        }
                    }

                    var blockIsRoot   = block == rootBlock;
                    var primaryDamage = primeDamage || blockIsRoot;

                    if (damagePool <= 0 && primaryDamage || objectsHit >= maxObjects)
                    {
                        break;
                    }

                    var scaledDamage = damagePool * damageScale;
                    if (primaryDamage)
                    {
                        if (countBlocksAsObjects)
                        {
                            objectsHit++;
                        }

                        if (scaledDamage <= blockHp)
                        {
                            outOfPew   = true;
                            damagePool = 0;
                        }
                        else
                        {
                            _destroyedSlims.Add(block);
                            if (IsClient)
                            {
                                _destroyedSlimsClient.Add(block);
                                if (_slimHealthClient.ContainsKey(block))
                                {
                                    _slimHealthClient.Remove(block);
                                }
                            }
                            damagePool -= blockHp;
                        }
                    }
                    else
                    {
                        scaledDamage = areaEffectDmg * damageScale;
                        if (scaledDamage >= blockHp)
                        {
                            _destroyedSlims.Add(block);
                            if (IsClient)
                            {
                                _destroyedSlimsClient.Add(block);
                                if (_slimHealthClient.ContainsKey(block))
                                {
                                    _slimHealthClient.Remove(block);
                                }
                            }
                        }
                    }

                    if (!IsClient)
                    {
                        block.DoDamage(scaledDamage, damageType, sync, null, attackerId);
                    }
                    else
                    {
                        var hasBlock = _slimHealthClient.ContainsKey(block);
                        if (hasBlock && _slimHealthClient[block] - scaledDamage > 0)
                        {
                            _slimHealthClient[block] -= scaledDamage;
                        }
                        else if (hasBlock)
                        {
                            _slimHealthClient.Remove(block);
                        }
                        else if (block.Integrity - scaledDamage > 0)
                        {
                            _slimHealthClient[block] = blockHp - scaledDamage;
                        }
                    }

                    var theEnd = damagePool <= 0 || objectsHit >= maxObjects;

                    if (explosive && (!detonateOnEnd && blockIsRoot || detonateOnEnd && theEnd))
                    {
                        var rootPos = grid.GridIntegerToWorld(rootBlock.Position);
                        if (areaEffectDmg > 0)
                        {
                            SUtils.CreateMissileExplosion(this, areaEffectDmg * damageScale, areaRadius, rootPos, hitEnt.Intersection.Direction, attacker, grid, t.AmmoDef, true);
                        }
                        if (detonateOnEnd && theEnd)
                        {
                            SUtils.CreateMissileExplosion(this, detonateDmg * damageScale, detonateRadius, rootPos, hitEnt.Intersection.Direction, attacker, grid, t.AmmoDef, true);
                        }
                    }
                    else if (!nova)
                    {
                        if (hitMass > 0 && blockIsRoot)
                        {
                            var speed = t.AmmoDef.Trajectory.DesiredSpeed > 0 ? t.AmmoDef.Trajectory.DesiredSpeed : 1;
                            ApplyProjectileForce(grid, grid.GridIntegerToWorld(rootBlock.Position), hitEnt.Intersection.Direction, (hitMass * speed));
                        }

                        if (radiantBomb && theEnd)
                        {
                            nova = true;
                            i--;
                            t.BaseDamagePool = 0;
                            t.ObjectsHit     = maxObjects;
                            objectsHit       = int.MinValue;
                            var aInfo = t.AmmoDef.AreaEffect;
                            var dInfo = aInfo.Detonation;

                            if (dInfo.DetonationDamage > 0)
                            {
                                damagePool = detonateDmg;
                            }
                            else if (aInfo.AreaEffectDamage > 0)
                            {
                                damagePool = areaEffectDmg;
                            }
                            else
                            {
                                damagePool = scaledDamage;
                            }
                            break;
                        }
                    }
                }
            }
            if (!countBlocksAsObjects)
            {
                t.ObjectsHit += 1;
            }
            if (!nova)
            {
                t.BaseDamagePool = damagePool;
                t.ObjectsHit     = objectsHit;
            }
            if (radiantCascade || nova)
            {
                _slimsSortedList.Clear();
            }
            hitEnt.Blocks.Clear();
        }
コード例 #12
0
        public override void onAfterPaste(MMEventArgs aArgs)
        {
            Document _doc = aArgs.Document;

            // if boundary selected
            if (_doc.Selection.HasBoundary && !_doc.Selection.HasTopic) //if any topic in selection, any boundaries are ignored
            {
                Boundary bnd = null;
                foreach (Boundary b in _doc.Selection)
                {
                    bnd = b; // take the first one
                    break;
                }
                aArgs.target = bnd.Topic;
                aArgs.what   = "boundary";
                onObjectChanged(aArgs);
                _doc = null;
                bnd  = null;
                return;
            }

            MapCompanion.publishpaste = true;
            Topic _t = null;

            foreach (DocumentObject obj in _doc.Selection) // находим "верхний" топик в выборе
            {
                _t = obj as Topic;
                if (_t == null)
                {
                    continue;
                }

                aArgs.target = _t;
                ProcessBranch(_t);
                onObjectAdded(aArgs);
            }
            _t   = null;
            _doc = null;

            string rootfolder = aArgs.aMapFolderPath + "share\\";
            string _path;

            // Process relationships if any
            if (!restrict)
            {
                foreach (Relationship r in BranchRelationships) // list of branch relationships
                {
                    _path = rootfolder + SUtils.modtime + "&" + SUtils.currentUserName + ".txt";

                    SUtils.ProcessRelationship(r, _path, "relationship:paste");

                    foreach (Topic callout in r.AllCalloutTopics)
                    {
                        RelationshipTopics(callout, aArgs);
                    }
                }
            }

            for (int i = 0; i <= BranchRelationships.Count; i++)
            {
                BranchRelationships[i] = null; // TODO needed?
            }
            BranchRelationships.Clear();
        }
コード例 #13
0
        public override void onObjectAdded(MMEventArgs aArgs) // only for new topics
        {
            Topic        _t = aArgs.target as Topic;
            Relationship _r = aArgs.target as Relationship;
            Boundary     _b = aArgs.target as Boundary;

            string rootfolder = aArgs.aMapFolderPath + "share\\";
            string _path      = rootfolder + SUtils.modtime + "&" + SUtils.currentUserName + ".txt";
            string _what      = "add:";
            string pGuid      = "";
            string offset     = "";
            int    a          = 0;

            if (_r != null) // add relationship
            {
                SUtils.ProcessRelationship(_r, _path, "relationship:add");
                _r = null;
                return;
            }
            if (_b != null) // add boundary
            {
                SUtils.ProcessBoundary(_b, _path, "boundary:add");
                System.Threading.Thread.Sleep(100); // иначе выноска границы может вперед прийти по облачному хранилищу
                _b = null;
                return;
            }

            if (_t == null)
            {
                return; // TODO case?
            }
            if (_t.IsFloatingTopic)
            {
                _what = "add:floating";
            }

            if (_t.IsCalloutTopic || _t.IsSummaryTopic)
            {
                _what = "add:callout";
                if (_t.ParentRelationship != null) // add callout to relationship
                {
                    _what = "add:relcallout";
                    Relationship rel = _t.ParentRelationship;
                    pGuid = rel.get_Attributes(SUtils.SYNERGYNAMESPACE).GetAttributeValue(SUtils.OGUID);
                }
                if (_t.ParentBoundary != null) // add callout to boundary
                {
                    _what = "add:bndcallout";
                    Boundary bnd = _t.ParentBoundary;
                    pGuid = bnd.get_Attributes(SUtils.SYNERGYNAMESPACE).GetAttributeValue(SUtils.OGUID);
                }
            }

            if (_t.IsFloatingTopic || _t.IsMainTopic || _t.IsCalloutTopic)
            {
                float x, y;
                _t.GetOffset(out x, out y);
                offset = x.ToString() + ";" + y.ToString();
                if (_t.IsMainTopic)
                {
                    a = -1;
                }
            }
            if (!_t.IsFloatingTopic && _what != "add:relcallout" && _what != "add:bndcallout")
            {
                pGuid = _t.ParentTopic.get_Attributes(SUtils.SYNERGYNAMESPACE).GetAttributeValue(SUtils.OGUID);
                a     = MMUtils.SubtopicIndex(_t);
            }

            if (!_t.IsCalloutTopic && !_t.IsFloatingTopic && !_t.IsSummaryTopic)
            {
                _what = _what + a.ToString();
            }

            string _shorttext = MMUtils.TShortText(_t.Text);

            TransactionsWrapper.SetAttributes(_t);

            string _tGuid     = _t.Guid;
            string _topicdata = "";

            if (_t.IsDefaultTopicText)
            {
                _topicdata = "newtopic";
            }
            else
            {
                _topicdata = _t.Xml;
            }

            _t = null;

            try
            {
                StreamWriter sw = new StreamWriter(File.Create(_path));
                sw.WriteLine(_what);
                sw.WriteLine(pGuid);      // parent topic's guid - to which add topic(s)
                sw.WriteLine(_shorttext); // topic text or what added - for chat
                sw.WriteLine(_tGuid);
                sw.WriteLine(SUtils.TimeStamp + ";" + SUtils.currentUserName + ";" + SUtils.currentUserEmail);
                sw.WriteLine(offset); // for main, floating or callout topic
                sw.WriteLine(_topicdata);
                sw.Close();
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("Exception: " + e.Message, "SaveChanges:onObjectAdded");
            }
        }
コード例 #14
0
        ////////////////////////////////////////////////////////////////////////

        public override void onObjectChanged(MMEventArgs aArgs)
        {
            string _what = aArgs.what;

            Topic        _t = aArgs.target as Topic;
            Relationship _r = aArgs.target as Relationship;
            Boundary     _b = aArgs.target as Boundary;

            string rootfolder = aArgs.aMapFolderPath + "share\\";
            string _path      = rootfolder + SUtils.modtime + "&" + SUtils.currentUserName + ".txt";

            if (_r != null)
            {
                SUtils.ProcessRelationship(_r, _path, "relationship:modify");
                _r = null;
                return;
            }

            if (_b != null)
            {
                SUtils.ProcessBoundary(_b, _path, "boundary:modify");
                _b = null;
                return;
            }

            string rollup  = SUtils.rollupuri;
            string _offset = "";
            string _extra  = "";

            if (_t == null)
            {
                return; // TODO case?
            }
            _extra = aArgs.extra;
            //if (_extra != "")
            //    System.Windows.Forms.Clipboard.SetText(_extra); // TODO для чего?

            if (aArgs.extra.ToString() == rollup)
            {
                _what = "rollup";
                MapCompanion.rollup = true;
            }

            if (_t.IsFloatingTopic || _t.IsMainTopic || _t.IsCalloutTopic)
            {
                float x, y;
                _t.GetOffset(out x, out y);
                _offset = x.ToString() + ";" + y.ToString();
            }

            string _shorttext = MMUtils.TShortText(_t.Text);
            string _attrs     = SUtils.TimeStamp + ";" + SUtils.currentUserName + ";" + SUtils.currentUserEmail;

            TransactionsWrapper.SetATTR(_t, SUtils.TMODIFIED, _attrs);

            string tXML = MMUtils.getCleanTopicXML(_t.Xml);

            if (_what == "task")
            {
                _topicxml = tXML; // впадает в цикл, если изменять Duration, Effort и ресурсы
            }
            string _tguid = _t.get_Attributes(SUtils.SYNERGYNAMESPACE).GetAttributeValue(SUtils.OGUID);

            _t = null;

            try
            {
                StreamWriter sw = new StreamWriter(File.Create(_path));
                sw.WriteLine("modify:" + _what);
                sw.WriteLine(_tguid);
                sw.WriteLine(_shorttext); // short topic text for chat
                sw.WriteLine(_attrs);
                sw.WriteLine(_offset);
                sw.WriteLine(_extra);
                sw.Close();
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("Exception: " + e.Message, "SaveChanges:onObjectChanged");
            }
        }
コード例 #15
0
        private void DamageVoxel(HitEntity hitEnt, ProInfo info, bool canDamage)
        {
            var entity  = hitEnt.Entity;
            var destObj = hitEnt.Entity as MyVoxelBase;

            if (destObj == null || entity == null || !hitEnt.HitPos.HasValue)
            {
                return;
            }
            var shieldHeal = info.AmmoDef.DamageScales.Shields.Type == ShieldDef.ShieldType.Heal;

            if (!info.AmmoDef.Const.VoxelDamage || shieldHeal)
            {
                info.BaseDamagePool = 0;
                return;
            }

            using (destObj.Pin())
            {
                var detonateOnEnd = info.AmmoDef.Const.AmmoAreaEffect && info.AmmoDef.AreaEffect.Detonation.DetonateOnEnd && info.AmmoDef.AreaEffect.AreaEffect != AreaEffectType.Radiant;

                info.ObjectsHit++;
                float damageScale = 1;
                if (info.AmmoDef.Const.VirtualBeams)
                {
                    damageScale *= info.WeaponCache.Hits;
                }

                var scaledDamage = info.BaseDamagePool * damageScale;
                var fallOff      = info.AmmoDef.Const.FallOffScaling && info.DistanceTraveled > info.AmmoDef.DamageScales.FallOff.Distance;
                if (fallOff)
                {
                    var fallOffMultipler = (float)MathHelperD.Clamp(1.0 - ((info.DistanceTraveled - info.AmmoDef.DamageScales.FallOff.Distance) / (info.AmmoDef.Const.MaxTrajectory - info.AmmoDef.DamageScales.FallOff.Distance)), info.AmmoDef.DamageScales.FallOff.MinMultipler, 1);
                    scaledDamage *= fallOffMultipler;
                }

                var oRadius       = info.AmmoDef.AreaEffect.AreaEffectRadius;
                var minTestRadius = info.DistanceTraveled - info.PrevDistanceTraveled;
                var tRadius       = oRadius < minTestRadius ? minTestRadius : oRadius;
                var objHp         = (int)MathHelper.Clamp(MathFuncs.VolumeCube(MathFuncs.LargestCubeInSphere(tRadius)), 5000, double.MaxValue);


                if (tRadius > 5)
                {
                    objHp *= 5;
                }
                if (scaledDamage < objHp)
                {
                    var reduceBy = objHp / scaledDamage;
                    oRadius /= reduceBy;
                    if (oRadius < 1)
                    {
                        oRadius = 1;
                    }

                    info.BaseDamagePool = 0;
                }
                else
                {
                    info.BaseDamagePool -= objHp;
                    if (oRadius < minTestRadius)
                    {
                        oRadius = minTestRadius;
                    }
                }

                destObj.PerformCutOutSphereFast(hitEnt.HitPos.Value, (float)oRadius, true);
                //Log.Line($"TestHealth: {objHp} - tRadius:{tRadius} - oRadius:{oRadius} - travel:{minTestRadius} - base:{info.BaseDamagePool} - det:{detonateOnEnd}");

                if (detonateOnEnd && info.BaseDamagePool <= 0)
                {
                    var det     = info.AmmoDef.AreaEffect.Detonation;
                    var dRadius = det.DetonationRadius;
                    var dDamage = det.DetonationDamage;

                    //var dObjHp = (int)MathHelper.Clamp(MathFuncs.VolumeCube(MathFuncs.LargestCubeInSphere(dRadius)), 5000, double.MaxValue);
                    //if (dRadius > 5) dObjHp *= 5;
                    //dObjHp *= 5;
                    //var reduceBy = dObjHp / dDamage;
                    //dRadius /= reduceBy;

                    if (dRadius < 1.5)
                    {
                        dRadius = 1.5f;
                    }

                    //Log.Line($"radius: {det.DetonationRadius} - dRadius:{dRadius} - reduceBy:{reduceBy} - dObjHp:{dObjHp}");
                    if (canDamage)
                    {
                        //destObj.PerformCutOutSphereFast(hitEnt.HitPos.Value, dRadius, true);
                        SUtils.CreateMissileExplosion(this, dDamage, dRadius, hitEnt.HitPos.Value, hitEnt.Intersection.Direction, info.Target.FiringCube, destObj, info.AmmoDef, true);
                    }
                }
            }
        }