프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 154d8f43

이력 | 보기 | 이력해설 | 다운로드 (192 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Data;
7
using Llama;
8
using Plaice;
9
using Ingr.RAD2D.Interop.RAD2D;
10
using Ingr.RAD2D.Internal;
11
using Ingr.RAD2D.Helper;
12
using Converter.BaseModel;
13
using Converter.SPPID.Model;
14
using Converter.SPPID.Properties;
15
using Converter.SPPID.Util;
16
using Converter.SPPID.DB;
17
using Ingr.RAD2D.MacroControls.CmdCtrl;
18
using Ingr.RAD2D;
19
using System.Windows;
20
using System.Threading;
21
using System.Drawing;
22
using Microsoft.VisualBasic;
23
using Newtonsoft.Json;
24
using DevExpress.XtraSplashScreen;
25
namespace Converter.SPPID
26
{
27
    public class AutoModeling : IDisposable
28
    {
29
        Placement _placement;
30
        LMADataSource dataSource;
31
        string drawingID;
32
        dynamic newDrawing;
33
        dynamic application;
34
        bool closeDocument;
35
        Ingr.RAD2D.Application radApp;
36
        SPPID_Document document;
37
        ETCSetting _ETCSetting;
38

    
39
        public string DocumentLabelText { get; set; }
40

    
41
        List<Line> BranchLines = new List<Line>();
42
        List<string> ZeroLengthSymbolToSymbolModelItemID = new List<string>();
43
        List<string> ZeroLengthModelItemID = new List<string>();
44
        List<string> ZeroLengthModelItemIDReverse = new List<string>();
45
        List<Symbol> prioritySymbols;
46

    
47
        public AutoModeling(SPPID_Document document, bool closeDocument)
48
        {
49
            application = Interaction.GetObject("", "PIDAutomation.Application");
50
            WrapperApplication wApp = new WrapperApplication(application.Application);
51
            radApp = wApp.RADApplication;
52

    
53
            this.closeDocument = closeDocument;
54
            this.document = document;
55
            this._ETCSetting = ETCSetting.GetInstance();
56
        }
57

    
58
        private void SetSystemEditingCommand(bool value)
59
        {
60
            foreach (var item in radApp.Commands)
61
            {
62
                if (item.Argument == "SystemEditingCmd.SystemEditing")
63
                {
64
                    if (item.Checked != value)
65
                    {
66
                        radApp.RunMacro("systemeditingcmd.dll");
67
                        break;
68
                    }
69

    
70
                }
71
            }
72
        }
73

    
74
        /// <summary>
75
        /// 도면 단위당 실행되는 메서드
76
        /// </summary>
77
        public void Run()
78
        {
79
            string drawingNumber = document.DrawingNumber;
80
            string drawingName = document.DrawingName;
81
            try
82
            {
83
                _placement = new Placement();
84
                dataSource = _placement.PIDDataSource;
85

    
86
                if (CreateDocument(ref drawingNumber, ref drawingName) && DocumentCoordinateCorrection())
87
                {
88
                    Log.Write("Start Modeling");
89
                    SplashScreenManager.ShowForm(typeof(SPPIDSplashScreen), true, true);
90
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetParent, (IntPtr)radApp.HWnd);
91
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllStepCount, 18);
92
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
93

    
94
                    // Equipment Modeling
95
                    RunEquipmentModeling();
96
                    // Symbol Modeling
97
                    RunSymbolModeling();
98
                    // LineRun Line Modeling
99
                    RunLineModeling();
100
                    // Clear Attribute
101
                    RunClearValueInconsistancy();
102
                    // EndBreak Modeling
103
                    RunEndBreakModeling();
104
                    // SpecBreak Modeling
105
                    RunSpecBreakModeling();
106
                    // Join SameConnector
107
                    RunJoinRunForSameConnector();
108
                    // Join Run
109
                    RunJoinRun();
110
                    // Check FlowDirection
111
                    RunFlowDirection();
112
                    //Line Number Modeling
113
                    RunLineNumberModeling();
114
                    // Note Modeling
115
                    RunNoteModeling();
116
                    // Text Modeling
117
                    RunTextModeling();
118
                    // Input LineNumber Attribute
119
                    RunInputLineNumberAttribute();
120
                    // Input Symbol Attribute
121
                    RunInputSymbolAttribute();
122
                    // Input SpecBreak Attribute
123
                    RunInputSpecBreakAttribute();
124
                    // Label Symbol Modeling
125
                    RunLabelSymbolModeling();
126

    
127
                    // Result Logging
128
                    document.CheckModelingResult();
129
                }
130
            }
131
            catch (Exception ex)
132
            {
133
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
134
                {
135
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
136
                    SplashScreenManager.CloseForm(false);
137
                    Log.Write("\r\n");
138
                }
139
                System.Windows.Forms.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
140
            }
141
            finally
142
            {
143
                Project_DB.InsertDrawingInfoAndOPCInfo(document.PATH, drawingNumber, drawingName, document);
144
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
145
                {
146
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
147
                    SplashScreenManager.CloseForm(false);
148
                    Log.Write("\r\n");
149
                }
150
                Thread.Sleep(1000);
151

    
152
                Log.Write("End Modeling");
153
                radApp.ActiveWindow.Fit();
154

    
155
                ReleaseCOMObjects(application);
156
                application = null;
157
                if (radApp.ActiveDocument != null)
158
                {
159
                    if (closeDocument && newDrawing != null)
160
                    {
161
                        newDrawing.Save();
162
                        newDrawing.CloseDrawing(true);
163
                        ReleaseCOMObjects(newDrawing);
164
                        newDrawing = null;
165
                    }
166
                    else if (newDrawing == null)
167
                    {
168
                        Log.Write("error document");
169
                    }
170
                }
171

    
172
                ReleaseCOMObjects(dataSource);
173
                dataSource = null;
174
                ReleaseCOMObjects(_placement);
175
                _placement = null;
176

    
177
                Thread.Sleep(1000);
178
            }
179
        }
180

    
181
        private void RunEquipmentModeling()
182
        {
183
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
184
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
185
            foreach (Equipment item in document.Equipments)
186
            {
187
                try
188
                {
189
                    EquipmentModeling(item);
190
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
191
                }
192
                catch (Exception ex)
193
                {
194
                    Log.Write("Error in EquipmentModeling");
195
                    Log.Write("UID : " + item.UID);
196
                    Log.Write(ex.Message);
197
                    Log.Write(ex.StackTrace);
198
                }
199
            }
200
        }
201

    
202
        private void RunSymbolModeling()
203
        {
204
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
205
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
206
            prioritySymbols = GetPrioritySymbol();
207
            foreach (var item in prioritySymbols)
208
            {
209
                try
210
                {
211
                    SymbolModelingBySymbol(item);
212
                }
213
                catch (Exception ex)
214
                {
215
                    Log.Write("Error in SymbolModelingByPriority");
216
                    Log.Write("UID : " + item.UID);
217
                    Log.Write(ex.Message);
218
                    Log.Write(ex.StackTrace);
219
                }
220
            }
221
        }
222
        private void RunLineModeling()
223
        {
224
            List<Line> AllLine = document.LINES.ToList();
225
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
226
            !SPPIDUtil.IsBranchedLine(document, x));
227
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
228

    
229
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
230
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
231

    
232
            SetPriorityLine(step1_Line);
233
            foreach (var item in step1_Line)
234
            {
235
                try
236
                {
237
                    NewLineModeling(item);
238
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
239
                }
240
                catch (Exception ex)
241
                {
242
                    Log.Write("Error in NewLineModeling");
243
                    Log.Write("UID : " + item.UID);
244
                    Log.Write(ex.Message);
245
                    Log.Write(ex.StackTrace);
246
                }
247
            }
248

    
249
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
250
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 2");
251
            int branchCount = BranchLines.Count;
252
            while (BranchLines.Count > 0)
253
            {
254
                try
255
                {
256
                    SortBranchLines();
257
                    Line item = BranchLines[0];
258
                    NewLineModeling(item, true);
259
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
260
                }
261
                catch (Exception ex)
262
                {
263
                    Log.Write("Error in NewLineModeling");
264
                    Log.Write("UID : " + BranchLines[0].UID);
265
                    Log.Write(ex.Message);
266
                    Log.Write(ex.StackTrace);
267
                    break;
268
                }
269
            }
270

    
271
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
272
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
273
            foreach (var item in stepLast_Line)
274
            {
275
                try
276
                {
277
                    NewLineModeling(item);
278
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
279
                }
280
                catch (Exception ex)
281
                {
282
                    Log.Write("Error in NewLineModeling");
283
                    Log.Write("UID : " + item.UID);
284
                    Log.Write(ex.Message);
285
                    Log.Write(ex.StackTrace);
286
                }
287
            }
288
        }
289
        private void RunClearValueInconsistancy()
290
        {
291
            int count = 1;
292
            bool loop = true;
293
            while (loop)
294
            {
295
                loop = false;
296
                LMAFilter filter = new LMAFilter();
297
                LMACriterion criterion = new LMACriterion();
298
                filter.ItemType = "Relationship";
299
                criterion.SourceAttributeName = "SP_DRAWINGID";
300
                criterion.Operator = "=";
301
                criterion.set_ValueAttribute(drawingID);
302
                filter.get_Criteria().Add(criterion);
303

    
304
                LMRelationships relationships = new LMRelationships();
305
                relationships.Collect(dataSource, Filter: filter);
306

    
307
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
308
                if (count > 1)
309
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
310
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
311
                foreach (LMRelationship relationship in relationships)
312
                {
313
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
314
                    {
315
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
316
                        {
317
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
318
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
319
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
320
                            if (modelItem1 != null)
321
                            {
322
                                string attrName = array[0];
323
                                if (attrName.Contains("PipingPoint"))
324
                                {
325
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
326
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
327
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
328
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
329
                                    {
330
                                        loop = true;
331
                                        attribute1.set_Value(DBNull.Value);
332
                                    }
333
                                    attribute1 = null;
334
                                }
335
                                else
336
                                {
337
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
338
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
339
                                    {
340
                                        loop = true;
341
                                        attribute1.set_Value(DBNull.Value);
342
                                    }
343
                                    attribute1 = null;
344
                                }
345
                                modelItem1.Commit();
346
                            }
347
                            if (modelItem2 != null)
348
                            {
349
                                string attrName = array[1];
350
                                if (attrName.Contains("PipingPoint"))
351
                                {
352
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
353
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
354
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
355
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
356
                                    {
357
                                        attribute2.set_Value(DBNull.Value);
358
                                        loop = true;
359
                                    }
360
                                    attribute2 = null;
361
                                }
362
                                else
363
                                {
364
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
365
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
366
                                    {
367
                                        attribute2.set_Value(DBNull.Value);
368
                                        loop = true;
369
                                    }
370
                                    attribute2 = null;
371
                                }
372
                                modelItem2.Commit();
373
                            }
374
                            ReleaseCOMObjects(modelItem1);
375
                            modelItem1 = null;
376
                            ReleaseCOMObjects(modelItem2);
377
                            modelItem2 = null;
378
                            inconsistency.Commit();
379
                        }
380
                        ReleaseCOMObjects(inconsistency);
381
                    }
382
                    relationship.Commit();
383
                    ReleaseCOMObjects(relationship);
384
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
385
                }
386
                ReleaseCOMObjects(filter);
387
                filter = null;
388
                ReleaseCOMObjects(criterion);
389
                criterion = null;
390
                ReleaseCOMObjects(relationships);
391
                relationships = null;
392
                count++;
393
            }
394
        }
395
        private void RunEndBreakModeling()
396
        {
397
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
398
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
399
            foreach (var item in document.EndBreaks)
400
                try
401
                {
402
                    EndBreakModeling(item);
403
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
404
                }
405
                catch (Exception ex)
406
                {
407
                    Log.Write("Error in EndBreakModeling");
408
                    Log.Write("UID : " + item.UID);
409
                    Log.Write(ex.Message);
410
                    Log.Write(ex.StackTrace);
411
                }
412
        }
413
        private void RunSpecBreakModeling()
414
        {
415
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
416
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
417
            foreach (var item in document.SpecBreaks)
418
                try
419
                {
420
                    SpecBreakModeling(item);
421
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
422
                }
423
                catch (Exception ex)
424
                {
425
                    Log.Write("Error in SpecBreakModeling");
426
                    Log.Write("UID : " + item.UID);
427
                    Log.Write(ex.Message);
428
                    Log.Write(ex.StackTrace);
429
                }
430
        }
431
        private void RunJoinRunForSameConnector()
432
        {
433
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
434
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
435
            foreach (var line in document.LINES)
436
            {
437
                if (!SPPIDUtil.IsSegmentLine(document, line))
438
                {
439
                    foreach (var connector in line.CONNECTORS)
440
                    {
441
                        if (connector.ConnectedObject != null &&
442
                            connector.ConnectedObject.GetType() == typeof(Line) &&
443
                            !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
444
                        {
445
                            Line connLine = connector.ConnectedObject as Line;
446
                            if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(connLine.SPPID.ModelItemId))
447
                            {
448
                                string survivorId = string.Empty;
449
                                JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
450
                            }
451
                                
452
                        }
453
                    }
454
                }
455
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
456
            }
457
        }
458
        private void RunJoinRun()
459
        {
460
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
461
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
462
            List<string> endModelID = new List<string>();
463
            foreach (var line in document.LINES)
464
            {
465
                if (!endModelID.Contains(line.SPPID.ModelItemId))
466
                {
467
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
468
                    {
469
                        string survivorId = string.Empty;
470
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
471
                        if (string.IsNullOrEmpty(survivorId))
472
                        {
473
                            endModelID.Add(line.SPPID.ModelItemId);
474
                        }
475
                    }
476
                }
477
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
478
            }
479
        }
480
        private void RunLineNumberModeling()
481
        {
482
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
483
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
484
            foreach (var item in document.LINENUMBERS)
485
            {
486
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
487
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
488
                {
489
                    ReleaseCOMObjects(label);
490
                    item.SPPID.RepresentationId = null;
491
                    LineNumberModeling(item);
492
                }
493
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
494
            }
495
        }
496
        private void RunFlowDirection()
497
        {
498
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, 
499
                document.LINES.Count + ZeroLengthModelItemID.Count + ZeroLengthModelItemIDReverse.Count + ZeroLengthSymbolToSymbolModelItemID.Count);
500
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Check Flow Direction");
501
            foreach (var line in document.LINES)
502
            {
503
                if (!string.IsNullOrEmpty(line.SPPID.ModelItemId))
504
                {
505
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
506
                    if (modelItem != null && modelItem.get_ItemStatus() == "Active")
507
                    {
508
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
509
                        if (attribute != null)
510
                        {
511
                            attribute.set_Value("End 1 is upstream (Inlet)");
512
                            modelItem.Commit();
513
                        }
514

    
515
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
516

    
517
                        ReleaseCOMObjects(modelItem);
518
                        modelItem = null;
519
                    }
520
                }
521

    
522
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
523
            }
524
            foreach (var modelId in ZeroLengthModelItemID)
525
            {
526
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
527
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
528
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
529
                {
530
                    attribute.set_Value("End 1 is upstream (Inlet)");
531
                    zeroLengthModelItem.Commit();
532
                }
533

    
534
                SetFlowDirectionByLine(modelId);
535

    
536
                ReleaseCOMObjects(zeroLengthModelItem);
537
                zeroLengthModelItem = null;
538

    
539
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
540
            }
541
            foreach (var modelId in ZeroLengthModelItemIDReverse)
542
            {
543
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
544
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
545
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
546
                {
547
                    attribute.set_Value("End 1 is downstream (Outlet)");
548
                    zeroLengthModelItem.Commit();
549
                }
550

    
551
                SetFlowDirectionByLine(modelId);
552

    
553
                ReleaseCOMObjects(zeroLengthModelItem);
554
                zeroLengthModelItem = null;
555

    
556
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
557
            }
558
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
559
            {
560
                SetFlowDirectionByLine(modelId);
561
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
562
            }
563

    
564
            void SetFlowDirectionByLine(string lineModelItemID)
565
            {
566
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
567
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
568
                {
569
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
570
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
571
                    {
572
                        string sFlowDirection = attribute.get_Value().ToString();
573
                        foreach (LMRepresentation rep in modelItem.Representations)
574
                        {
575
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
576
                            {
577
                                LMConnector connector = dataSource.GetConnector(rep.Id);
578

    
579
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
580
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
581
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
582
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
583

    
584
                                ReleaseCOMObjects(connector);
585
                            }
586
                        }
587
                    }
588
                    ReleaseCOMObjects(modelItem);
589
                    modelItem = null;
590
                }
591

    
592
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
593
                {
594
                    // Item2가 Symbol
595
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
596
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
597
                    {
598
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
599
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
600
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
601

    
602
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
603

    
604
                        symbolModelItem.Commit();
605
                        ReleaseCOMObjects(symbolModelItem);
606
                        symbolModelItem = null;
607
                    }
608
                    // Item1이 Symbol
609
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
610
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
611
                    {
612
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
613
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
614
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
615

    
616
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
617

    
618
                        symbolModelItem.Commit();
619
                        ReleaseCOMObjects(symbolModelItem);
620
                        symbolModelItem = null;
621
                    }
622
                }
623

    
624
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
625
                {
626
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
627
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
628
                    if (attribute != null)
629
                    {
630
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
631
                            attribute.set_Value("End 1 is downstream (Outlet)");
632
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
633
                            attribute.set_Value("End 1 is upstream (Inlet)");
634
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
635
                            attribute.set_Value("End 1 is upstream (Inlet)");
636
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
637
                            attribute.set_Value("End 1 is downstream (Outlet)");
638
                    }
639
                }
640
            }
641
        }
642
        private void RunNoteModeling()
643
        {
644
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
645
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
646
            foreach (var item in document.NOTES)
647
                try
648
                {
649
                    NoteModeling(item);
650
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
651
                }
652
                catch (Exception ex)
653
                {
654
                    Log.Write("Error in NoteModeling");
655
                    Log.Write("UID : " + item.UID);
656
                    Log.Write(ex.Message);
657
                    Log.Write(ex.StackTrace);
658
                }
659
        }
660
        private void RunTextModeling()
661
        {
662
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
663
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
664
            foreach (var item in document.TEXTINFOS)
665
                try
666
                {
667
                    TextModeling(item);
668
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
669
                }
670
                catch (Exception ex)
671
                {
672
                    Log.Write("Error in TextModeling");
673
                    Log.Write("UID : " + item.UID);
674
                    Log.Write(ex.Message);
675
                    Log.Write(ex.StackTrace);
676
                }
677
        }
678
        private void RunInputLineNumberAttribute()
679
        {
680
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
681
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
682
            List<string> endLine = new List<string>();
683
            foreach (var item in document.LINENUMBERS)
684
                try
685
                {
686
                    InputLineNumberAttribute(item, endLine);
687
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
688
                }
689
                catch (Exception ex)
690
                {
691
                    Log.Write("Error in InputLineNumberAttribute");
692
                    Log.Write("UID : " + item.UID);
693
                    Log.Write(ex.Message);
694
                    Log.Write(ex.StackTrace);
695
                }
696
        }
697
        private void RunInputSymbolAttribute()
698
        {
699
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
700
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
701
            foreach (var item in document.SYMBOLS)
702
                try
703
                {
704
                    InputSymbolAttribute(item, item.ATTRIBUTES);
705
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
706
                }
707
                catch (Exception ex)
708
                {
709
                    Log.Write("Error in InputSymbolAttribute");
710
                    Log.Write("UID : " + item.UID);
711
                    Log.Write(ex.Message);
712
                    Log.Write(ex.StackTrace);
713
                }
714
        }
715
        private void RunInputSpecBreakAttribute()
716
        {
717
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
718
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
719
            foreach (var item in document.SpecBreaks)
720
                try
721
                {
722
                    InputSpecBreakAttribute(item);
723
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
724
                }
725
                catch (Exception ex)
726
                {
727
                    Log.Write("Error in InputSpecBreakAttribute");
728
                    Log.Write("UID : " + item.UID);
729
                    Log.Write(ex.Message);
730
                    Log.Write(ex.StackTrace);
731
                }
732
        }
733
        private void RunLabelSymbolModeling()
734
        {
735
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
736
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
737
            foreach (var item in document.SYMBOLS)
738
                try
739
                {
740
                    LabelSymbolModeling(item);
741
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
742
                }
743
                catch (Exception ex)
744
                {
745
                    Log.Write("Error in LabelSymbolModeling");
746
                    Log.Write("UID : " + item.UID);
747
                    Log.Write(ex.Message);
748
                    Log.Write(ex.StackTrace);
749
                }
750
        }
751
        
752
        /// <summary>
753
        /// 도면 생성 메서드
754
        /// </summary>
755
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
756
        {
757
            Log.Write("------------------ Start create document ------------------");
758
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
759
            Log.Write("Drawing name : " + drawingName);
760
            Log.Write("Drawing number : " + drawingNumber);
761
            Thread.Sleep(1000);
762
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
763
            if (newDrawing != null)
764
            {
765
                document.SPPID_DrawingNumber = drawingNumber;
766
                document.SPPID_DrawingName = drawingName;
767
                Thread.Sleep(1000);
768
                radApp.ActiveWindow.Fit();
769
                Thread.Sleep(1000);
770
                radApp.ActiveWindow.Zoom = 2000;
771
                Thread.Sleep(2000);
772

    
773
                //current LMDrawing 가져오기
774
                LMAFilter filter = new LMAFilter();
775
                LMACriterion criterion = new LMACriterion();
776
                filter.ItemType = "Drawing";
777
                criterion.SourceAttributeName = "Name";
778
                criterion.Operator = "=";
779
                criterion.set_ValueAttribute(drawingName);
780
                filter.get_Criteria().Add(criterion);
781

    
782
                LMDrawings drawings = new LMDrawings();
783
                drawings.Collect(dataSource, Filter: filter);
784

    
785
                drawingID = ((dynamic)drawings).Nth(1).Id;
786
                ReleaseCOMObjects(filter);
787
                ReleaseCOMObjects(criterion);
788
                ReleaseCOMObjects(drawings);
789
                filter = null;
790
                criterion = null;
791
                drawings = null;
792
            }
793
            else
794
                Log.Write("Fail Create Drawing");
795

    
796
            if (newDrawing != null)
797
                return true;
798
            else
799
                return false;
800
        }
801

    
802
        /// <summary>
803
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
804
        /// </summary>
805
        /// <param name="drawingName"></param>
806
        /// <param name="drawingNumber"></param>
807
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
808
        {
809
            LMDrawings drawings = new LMDrawings();
810
            drawings.Collect(dataSource);
811

    
812
            List<string> drawingNameList = new List<string>();
813
            List<string> drawingNumberList = new List<string>();
814

    
815
            foreach (LMDrawing item in drawings)
816
            {
817
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
818
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
819
            }
820

    
821
            int nameLength = drawingName.Length;
822
            while (drawingNameList.Contains(drawingName))
823
            {
824
                if (nameLength == drawingName.Length)
825
                    drawingName += "-1";
826
                else
827
                {
828
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
829
                    drawingName = drawingName.Substring(0, nameLength + 1);
830
                    drawingName += ++index;
831
                }
832
            }
833

    
834
            int numberLength = drawingNumber.Length;
835
            while (drawingNameList.Contains(drawingNumber))
836
            {
837
                if (numberLength == drawingNumber.Length)
838
                    drawingNumber += "-1";
839
                else
840
                {
841
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
842
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
843
                    drawingNumber += ++index;
844
                }
845
            }
846
            ReleaseCOMObjects(drawings);
847
            drawings = null;
848
        }
849

    
850
        /// <summary>
851
        /// 도면 크기 구하는 메서드
852
        /// </summary>
853
        /// <returns></returns>
854
        private bool DocumentCoordinateCorrection()
855
        {
856
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
857
            {
858
                Log.Write("Setting Drawing X, Drawing Y");
859
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
860
                Log.Write("Start coordinate correction");
861
                document.CoordinateCorrection();
862
                return true;
863
            }
864
            else
865
            {
866
                Log.Write("Need Drawing X, Y");
867
                return false;
868
            }
869
        }
870

    
871
        /// <summary>
872
        /// 심볼을 실제로 Modeling 메서드
873
        /// </summary>
874
        /// <param name="symbol">생성할 심볼</param>
875
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
876
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
877
        {
878
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
879
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
880
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
881
                return;
882
            // 이미 모델링 됐을 경우
883
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
884
                return;
885

    
886
            LMSymbol _LMSymbol = null;
887

    
888
            string mappingPath = symbol.SPPID.MAPPINGNAME;
889
            double x = symbol.SPPID.ORIGINAL_X;
890
            double y = symbol.SPPID.ORIGINAL_Y;
891
            int mirror = 0;
892
            double angle = symbol.ANGLE;
893

    
894
            // OPC 일경우 180도 일때 Mirror
895
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
896
                mirror = 1;
897

    
898
            // Mirror 계산
899
            if (symbol.FLIP == 1)
900
            {
901
                mirror = 1;
902
                angle += Math.PI;
903
            }
904

    
905
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
906
            {
907
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
908
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
909
                if (connector != null)
910
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
911

    
912
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
913

    
914
                if (_LMSymbol != null && _TargetItem != null)
915
                {
916
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
917

    
918
                    if (SPPIDUtil.IsSegmentLine(document, symbol, targetSymbol))
919
                    {
920
                        LMConnector reModelingConnector = FindBreakLineTarget(symbol, targetSymbol);
921
                        if (reModelingConnector != null)
922
                            ReModelingLMConnector(reModelingConnector);
923
                    }
924
                }
925

    
926
                ReleaseCOMObjects(_TargetItem);
927
            }
928
            else
929
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
930

    
931
            if (_LMSymbol != null)
932
            {
933
                _LMSymbol.Commit();
934

    
935
                // ConnCheck
936
                List<string> ids = new List<string>();
937
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
938
                {
939
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
940
                        ids.Add(item.Id);
941
                    ReleaseCOMObjects(item);
942
                }
943
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
944
                {
945
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
946
                        ids.Add(item.Id);
947
                    ReleaseCOMObjects(item);
948
                }
949

    
950
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
951
                if (targetSymbol == null && ids.Count != createdSymbolCount)
952
                {
953
                    double currentX = _LMSymbol.get_XCoordinate();
954
                    double currentY = _LMSymbol.get_YCoordinate();
955

    
956

    
957
                }
958

    
959
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
960
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
961
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
962

    
963
                foreach (var item in symbol.ChildSymbols)
964
                    CreateChildSymbol(item, _LMSymbol, symbol);
965

    
966
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
967
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
968

    
969
                double[] range = null;
970
                GetSPPIDSymbolRange(symbol, ref range);
971
                symbol.SPPID.SPPID_Min_X = range[0];
972
                symbol.SPPID.SPPID_Min_Y = range[1];
973
                symbol.SPPID.SPPID_Max_X = range[2];
974
                symbol.SPPID.SPPID_Max_Y = range[3];
975

    
976
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
977
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
978
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
979
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
980

    
981
                ReleaseCOMObjects(_LMSymbol);
982
            }
983
        }
984

    
985
        private void RemoveSymbol(Symbol symbol)
986
        {
987
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
988
            {
989
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
990
                if (_LMSymbol != null)
991
                {
992
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
993
                    ReleaseCOMObjects(_LMSymbol);
994
                }
995
            }
996

    
997
            symbol.SPPID.RepresentationId = string.Empty;
998
            symbol.SPPID.ModelItemID = string.Empty;
999
            symbol.SPPID.SPPID_X = double.NaN;
1000
            symbol.SPPID.SPPID_Y = double.NaN;
1001
            symbol.SPPID.SPPID_Min_X = double.NaN;
1002
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1003
            symbol.SPPID.SPPID_Max_X = double.NaN;
1004
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1005
        }
1006

    
1007
        private void RemoveSymbol(List<Symbol> symbols)
1008
        {
1009
            foreach (var symbol in symbols)
1010
            {
1011
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1012
                {
1013
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1014
                    if (_LMSymbol != null)
1015
                    {
1016
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1017
                        ReleaseCOMObjects(_LMSymbol);
1018
                    }
1019
                }
1020

    
1021
                symbol.SPPID.RepresentationId = string.Empty;
1022
                symbol.SPPID.ModelItemID = string.Empty;
1023
                symbol.SPPID.SPPID_X = double.NaN;
1024
                symbol.SPPID.SPPID_Y = double.NaN;
1025
                symbol.SPPID.SPPID_Min_X = double.NaN;
1026
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1027
                symbol.SPPID.SPPID_Max_X = double.NaN;
1028
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1029
            }
1030
        }
1031

    
1032
        /// <summary>
1033
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1034
        /// </summary>
1035
        /// <param name="targetConnector"></param>
1036
        /// <param name="targetSymbol"></param>
1037
        /// <param name="x"></param>
1038
        /// <param name="y"></param>
1039
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1040
        {
1041
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1042

    
1043
            double[] range = null;
1044
            List<double[]> points = new List<double[]>();
1045
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1046
            double x1 = range[0];
1047
            double y1 = range[1];
1048
            double x2 = range[2];
1049
            double y2 = range[3];
1050

    
1051
            // Origin 기준 Connector의 위치차이
1052
            double sceneX = 0;
1053
            double sceneY = 0;
1054
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1055
            double originX = 0;
1056
            double originY = 0;
1057
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1058
            double gapX = originX - sceneX;
1059
            double gapY = originY - sceneY;
1060

    
1061
            // SPPID Symbol과 ID2 심볼의 크기 차이
1062
            double sizeWidth = 0;
1063
            double sizeHeight = 0;
1064
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1065
            if (sizeWidth == 0 || sizeHeight == 0)
1066
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1067

    
1068
            double percentX = (x2 - x1) / sizeWidth;
1069
            double percentY = (y2 - y1) / sizeHeight;
1070

    
1071
            double SPPIDgapX = gapX * percentX;
1072
            double SPPIDgapY = gapY * percentY;
1073

    
1074
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1075
            double distance = double.MaxValue;
1076
            double[] resultPoint;
1077
            foreach (var point in points)
1078
            {
1079
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1080
                if (distance > result)
1081
                {
1082
                    distance = result;
1083
                    resultPoint = point;
1084
                    x = point[0];
1085
                    y = point[1];
1086
                }
1087
            }
1088

    
1089
            ReleaseCOMObjects(_TargetItem);
1090
        }
1091

    
1092
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1093
        {
1094
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1095
            if (index == 0)
1096
            {
1097
                x = targetLine.SPPID.START_X;
1098
                y = targetLine.SPPID.START_Y;
1099
            }
1100
            else
1101
            {
1102
                x = targetLine.SPPID.END_X;
1103
                y = targetLine.SPPID.END_Y;
1104
            }
1105
        }
1106

    
1107
        /// <summary>
1108
        /// SPPID Symbol의 Range를 구한다.
1109
        /// </summary>
1110
        /// <param name="symbol"></param>
1111
        /// <param name="range"></param>
1112
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1113
        {
1114
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1115
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1116
            double x1 = 0;
1117
            double y1 = 0;
1118
            double x2 = 0;
1119
            double y2 = 0;
1120
            symbol2d.Range(out x1, out y1, out x2, out y2);
1121
            range = new double[] { x1, y1, x2, y2 };
1122

    
1123
            for (int i = 1; i < int.MaxValue; i++)
1124
            {
1125
                double connX = 0;
1126
                double connY = 0;
1127
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1128
                    points.Add(new double[] { connX, connY });
1129
                else
1130
                    break;
1131
            }
1132

    
1133
            foreach (var childSymbol in symbol.ChildSymbols)
1134
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1135

    
1136
            ReleaseCOMObjects(_TargetItem);
1137
        }
1138

    
1139
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range)
1140
        {
1141
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1142
            if (_TargetItem != null)
1143
            {
1144
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1145
                double x1 = 0;
1146
                double y1 = 0;
1147
                double x2 = 0;
1148
                double y2 = 0;
1149
                symbol2d.Range(out x1, out y1, out x2, out y2);
1150
                range = new double[] { x1, y1, x2, y2 };
1151

    
1152
                foreach (var childSymbol in symbol.ChildSymbols)
1153
                    GetSPPIDChildSymbolRange(childSymbol, ref range);
1154

    
1155
                ReleaseCOMObjects(_TargetItem);
1156
            }
1157
        }
1158

    
1159
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1160
        {
1161
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1162
            foreach (var symbol in symbols)
1163
            {
1164
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1165
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1166
                double x1 = 0;
1167
                double y1 = 0;
1168
                double x2 = 0;
1169
                double y2 = 0;
1170
                symbol2d.Range(out x1, out y1, out x2, out y2);
1171

    
1172
                tempRange[0] = Math.Min(tempRange[0], x1);
1173
                tempRange[1] = Math.Min(tempRange[1], y1);
1174
                tempRange[2] = Math.Max(tempRange[2], x2);
1175
                tempRange[3] = Math.Max(tempRange[3], y2);
1176

    
1177
                foreach (var childSymbol in symbol.ChildSymbols)
1178
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1179

    
1180
                ReleaseCOMObjects(_TargetItem);
1181
            }
1182

    
1183
            range = tempRange;
1184
        }
1185

    
1186
        /// <summary>
1187
        /// Child Modeling 된 Symbol의 Range를 구한다.
1188
        /// </summary>
1189
        /// <param name="childSymbol"></param>
1190
        /// <param name="range"></param>
1191
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1192
        {
1193
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1194
            if (_ChildSymbol != null)
1195
            {
1196
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1197
                double x1 = 0;
1198
                double y1 = 0;
1199
                double x2 = 0;
1200
                double y2 = 0;
1201
                symbol2d.Range(out x1, out y1, out x2, out y2);
1202
                range[0] = Math.Min(range[0], x1);
1203
                range[1] = Math.Min(range[1], y1);
1204
                range[2] = Math.Max(range[2], x2);
1205
                range[3] = Math.Max(range[3], y2);
1206

    
1207
                for (int i = 1; i < int.MaxValue; i++)
1208
                {
1209
                    double connX = 0;
1210
                    double connY = 0;
1211
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1212
                        points.Add(new double[] { connX, connY });
1213
                    else
1214
                        break;
1215
                }
1216

    
1217
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1218
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1219

    
1220
                ReleaseCOMObjects(_ChildSymbol);
1221
            }
1222
        }
1223

    
1224
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1225
        {
1226
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1227
            if (_ChildSymbol != null)
1228
            {
1229
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1230
                double x1 = 0;
1231
                double y1 = 0;
1232
                double x2 = 0;
1233
                double y2 = 0;
1234
                symbol2d.Range(out x1, out y1, out x2, out y2);
1235
                range[0] = Math.Min(range[0], x1);
1236
                range[1] = Math.Min(range[1], y1);
1237
                range[2] = Math.Max(range[2], x2);
1238
                range[3] = Math.Max(range[3], y2);
1239

    
1240
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1241
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1242
                ReleaseCOMObjects(_ChildSymbol);
1243
            }
1244
        }
1245

    
1246
        /// <summary>
1247
        /// Label Symbol Modeling
1248
        /// </summary>
1249
        /// <param name="symbol"></param>
1250
        private void LabelSymbolModeling(Symbol symbol)
1251
        {
1252
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1253
            {
1254
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1255
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1256
                    return;
1257
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1258

    
1259
                string symbolUID = itemAttribute.VALUE;
1260
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1261
                if (targetItem != null &&
1262
                    (targetItem.GetType() == typeof(Symbol) ||
1263
                    targetItem.GetType() == typeof(Equipment)))
1264
                {
1265
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1266
                    string sRep = null;
1267
                    if (targetItem.GetType() == typeof(Symbol))
1268
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1269
                    else if (targetItem.GetType() == typeof(Equipment))
1270
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1271
                    if (!string.IsNullOrEmpty(sRep))
1272
                    {
1273
                        // LEADER Line 검사
1274
                        bool leaderLine = false;
1275
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1276
                        if (symbolMapping != null)
1277
                            leaderLine = symbolMapping.LEADERLINE;
1278

    
1279
                        // Target Symbol Item 가져오고 Label Modeling
1280
                        LMSymbol _TargetItem = dataSource.GetSymbol(sRep);
1281
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: _TargetItem.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1282

    
1283
                        //Leader 선 센터로
1284
                        if (_LMLabelPresist != null)
1285
                        {
1286
                            // Target Item에 Label의 Attribute Input
1287
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1288

    
1289
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1290
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1291
                            if (dependency != null)
1292
                            {
1293
                                bool result = false;
1294
                                foreach (var attributes in dependency.AttributeSets)
1295
                                {
1296
                                    foreach (var attribute in attributes)
1297
                                    {
1298
                                        string name = attribute.Name;
1299
                                        string value = attribute.GetValue().ToString();
1300
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1301
                                        {
1302
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1303
                                            {
1304
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1305
                                                {
1306
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1307
                                                    double prevX = _TargetItem.get_XCoordinate();
1308
                                                    double prevY = _TargetItem.get_YCoordinate();
1309
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1310
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1311
                                                    result = true;
1312
                                                    break;
1313
                                                }
1314
                                            }
1315
                                        }
1316

    
1317
                                        if (result)
1318
                                            break;
1319
                                    }
1320

    
1321
                                    if (result)
1322
                                        break;
1323
                                }
1324
                            }
1325

    
1326
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1327
                            _LMLabelPresist.Commit();
1328
                            ReleaseCOMObjects(_LMLabelPresist);
1329
                        }
1330

    
1331
                        ReleaseCOMObjects(_TargetItem);
1332
                    }
1333
                }
1334
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1335
                {
1336
                    Line targetLine = targetItem as Line;
1337
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1338
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1339
                    if (connectedLMConnector != null)
1340
                    {
1341
                        // LEADER Line 검사
1342
                        bool leaderLine = false;
1343
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1344
                        if (symbolMapping != null)
1345
                            leaderLine = symbolMapping.LEADERLINE;
1346

    
1347
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1348
                        if (_LMLabelPresist != null)
1349
                        {
1350
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1351
                            _LMLabelPresist.Commit();
1352
                            ReleaseCOMObjects(_LMLabelPresist);
1353
                        }
1354
                        ReleaseCOMObjects(connectedLMConnector);
1355
                    }
1356

    
1357
                    foreach (var item in connectorVertices)
1358
                        if (item.Key != null)
1359
                            ReleaseCOMObjects(item.Key);
1360
                }
1361
            }
1362
        }
1363

    
1364
        /// <summary>
1365
        /// Equipment를 실제로 Modeling 메서드
1366
        /// </summary>
1367
        /// <param name="equipment"></param>
1368
        private void EquipmentModeling(Equipment equipment)
1369
        {
1370
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1371
                return;
1372

    
1373
            LMSymbol _LMSymbol = null;
1374
            LMSymbol targetItem = null;
1375
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1376
            double x = equipment.SPPID.ORIGINAL_X;
1377
            double y = equipment.SPPID.ORIGINAL_Y;
1378
            int mirror = 0;
1379
            double angle = equipment.ANGLE;
1380

    
1381
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1382

    
1383
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1384
            if (connector != null)
1385
            {
1386
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1387
                if (connEquipment != null)
1388
                {
1389
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1390
                        EquipmentModeling(connEquipment);
1391

    
1392
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1393
                    {
1394
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1395
                        if (targetItem != null)
1396
                        {
1397
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1398
                        }
1399
                        else
1400
                        {
1401
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1402
                        }
1403
                    }
1404
                    else
1405
                    {
1406
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1407
                    }
1408
                }
1409
                else
1410
                {
1411
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1412
                }
1413
            }
1414
            else
1415
            {
1416
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1417
            }
1418

    
1419
            if (_LMSymbol != null)
1420
            {
1421
                _LMSymbol.Commit();
1422
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1423
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1424
                ReleaseCOMObjects(_LMSymbol);
1425
            }
1426

    
1427
            if (targetItem != null)
1428
            {
1429
                ReleaseCOMObjects(targetItem);
1430
            }
1431

    
1432
            ReleaseCOMObjects(_LMSymbol);
1433
        }
1434

    
1435
        /// <summary>
1436
        /// 첫 진입점
1437
        /// </summary>
1438
        /// <param name="symbol"></param>
1439
        private void SymbolModelingBySymbol(Symbol symbol)
1440
        {
1441
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1442
            List<object> endObjects = new List<object>();
1443
            endObjects.Add(symbol);
1444

    
1445
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1446
            foreach (var connector in symbol.CONNECTORS)
1447
            {
1448
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1449
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1450
                {
1451
                    endObjects.Add(connItem);
1452
                    if (connItem.GetType() == typeof(Symbol))
1453
                    {
1454
                        Symbol connSymbol = connItem as Symbol;
1455
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1456
                        {
1457
                            SymbolModeling(connSymbol, symbol);
1458
                        }
1459
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1460
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1461
                    }
1462
                    else if (connItem.GetType() == typeof(Line))
1463
                    {
1464
                        Line connLine = connItem as Line;
1465
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1466
                    }
1467
                }
1468
            }
1469
        }
1470

    
1471
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1472
        {
1473
            foreach (var connector in symbol.CONNECTORS)
1474
            {
1475
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1476
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1477
                {
1478
                    if (!endObjects.Contains(connItem))
1479
                    {
1480
                        endObjects.Add(connItem);
1481
                        if (connItem.GetType() == typeof(Symbol))
1482
                        {
1483
                            Symbol connSymbol = connItem as Symbol;
1484
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1485
                            {
1486
                                SymbolModeling(connSymbol, symbol);
1487
                            }
1488
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1489
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1490
                        }
1491
                        else if (connItem.GetType() == typeof(Line))
1492
                        {
1493
                            Line connLine = connItem as Line;
1494
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1495
                        }
1496
                    }
1497
                }
1498
            }
1499
        }
1500

    
1501
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1502
        {
1503
            foreach (var connector in line.CONNECTORS)
1504
            {
1505
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1506
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1507
                {
1508
                    if (!endObjects.Contains(connItem))
1509
                    {
1510
                        endObjects.Add(connItem);
1511
                        if (connItem.GetType() == typeof(Symbol))
1512
                        {
1513
                            Symbol connSymbol = connItem as Symbol;
1514
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1515
                            {
1516
                                List<Symbol> group = new List<Symbol>();
1517
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1518
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1519
                                List<Symbol> endModelingGroup = new List<Symbol>();
1520
                                if (priority != null)
1521
                                {
1522
                                    SymbolGroupModeling(priority, group);
1523

    
1524
                                    // Range 겹치는지 확인해야함
1525
                                    double[] prevRange = null;
1526
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1527
                                    double[] groupRange = null;
1528
                                    GetSPPIDSymbolRange(group, ref groupRange);
1529

    
1530
                                    double distanceX = 0;
1531
                                    double distanceY = 0;
1532
                                    bool overlapX = false;
1533
                                    bool overlapY = false;
1534
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1535
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1536
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1537
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1538
                                    {
1539
                                        RemoveSymbol(group);
1540
                                        foreach (var _temp in group)
1541
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1542

    
1543
                                        SymbolGroupModeling(priority, group);
1544
                                    }
1545
                                }
1546
                                else
1547
                                {
1548
                                    SymbolModeling(connSymbol, null);
1549
                                    // Range 겹치는지 확인해야함
1550
                                    double[] prevRange = null;
1551
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1552
                                    double[] connRange = null;
1553
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1554

    
1555
                                    double distanceX = 0;
1556
                                    double distanceY = 0;
1557
                                    bool overlapX = false;
1558
                                    bool overlapY = false;
1559
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1560
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1561
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1562
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1563
                                    {
1564
                                        RemoveSymbol(connSymbol);
1565
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1566

    
1567
                                        SymbolModeling(connSymbol, null);
1568
                                    }
1569
                                }
1570
                            }
1571
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1572
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1573
                        }
1574
                        else if (connItem.GetType() == typeof(Line))
1575
                        {
1576
                            Line connLine = connItem as Line;
1577
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1578
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1579
                        }
1580
                    }
1581
                }
1582
            }
1583
        }
1584

    
1585
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1586
        {
1587
            List<Symbol> endModelingGroup = new List<Symbol>();
1588
            SymbolModeling(firstSymbol, null);
1589
            endModelingGroup.Add(firstSymbol);
1590
            while (endModelingGroup.Count != group.Count)
1591
            {
1592
                foreach (var _symbol in group)
1593
                {
1594
                    if (!endModelingGroup.Contains(_symbol))
1595
                    {
1596
                        foreach (var _connector in _symbol.CONNECTORS)
1597
                        {
1598
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
1599
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
1600
                            {
1601
                                SymbolModeling(_symbol, _connSymbol);
1602
                                endModelingGroup.Add(_symbol);
1603
                                break;
1604
                            }
1605
                        }
1606
                    }
1607
                }
1608
            }
1609
        }
1610

    
1611
        /// <summary>
1612
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
1613
        /// </summary>
1614
        /// <param name="childSymbol"></param>
1615
        /// <param name="parentSymbol"></param>
1616
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
1617
        {
1618
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
1619
            double x1 = 0;
1620
            double x2 = 0;
1621
            double y1 = 0;
1622
            double y2 = 0;
1623
            symbol2d.Range(out x1, out y1, out x2, out y2);
1624

    
1625
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
1626
            if (_LMSymbol != null)
1627
            {
1628
                _LMSymbol.Commit();
1629
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1630
                foreach (var item in childSymbol.ChildSymbols)
1631
                    CreateChildSymbol(item, _LMSymbol, parent);
1632
            }
1633

    
1634

    
1635
            ReleaseCOMObjects(_LMSymbol);
1636
        }
1637
        double index = 0;
1638
        private void NewLineModeling(Line line, bool isBranchModeling = false)
1639
        {
1640
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
1641
                return;
1642

    
1643
            List<Line> group = new List<Line>();
1644
            GetConnectedLineGroup(line, group);
1645
            LineCoordinateCorrection(group);
1646

    
1647
            foreach (var groupLine in group)
1648
            {
1649
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
1650
                {
1651
                    BranchLines.Add(groupLine);
1652
                    continue;
1653
                }
1654

    
1655
                bool diagonal = false;
1656
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
1657
                    diagonal = true;
1658
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
1659
                LMSymbol _LMSymbolStart = null;
1660
                LMSymbol _LMSymbolEnd = null;
1661
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1662
                foreach (var connector in groupLine.CONNECTORS)
1663
                {
1664
                    double x = 0;
1665
                    double y = 0;
1666
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
1667
                    if (connector.ConnectedObject == null)
1668
                    {
1669
                        placeRunInputs.AddPoint(x, y);
1670
                    }
1671
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
1672
                    {
1673
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
1674
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
1675
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1676
                        {
1677
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
1678
                            if (_LMSymbolStart != null)
1679
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
1680
                            else
1681
                                placeRunInputs.AddPoint(x, y);
1682
                        }
1683
                        else
1684
                        {
1685
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
1686
                            if (_LMSymbolEnd != null)
1687
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
1688
                            else
1689
                                placeRunInputs.AddPoint(x, y);
1690
                        }
1691
                    }
1692
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
1693
                    {
1694
                        Line targetLine = connector.ConnectedObject as Line;
1695
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
1696
                        {
1697
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
1698
                            if (targetConnector != null)
1699
                            {
1700
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
1701
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1702
                            }
1703
                            else
1704
                            {
1705
                                placeRunInputs.AddPoint( x, y);
1706
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1707
                            }
1708
                        }
1709
                        else
1710
                        {
1711
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1712
                            {
1713
                                index += 0.01;
1714
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1715
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1716
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1717
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1718
                                else
1719
                                {
1720
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
1721
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1722
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1723
                                    else
1724
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1725
                                }
1726
                            }
1727

    
1728
                            placeRunInputs.AddPoint(x, y);
1729

    
1730
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
1731
                            {
1732
                                index += 0.01;
1733
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1734
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1735
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1736
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1737
                                else
1738
                                {
1739
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
1740
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1741
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1742
                                    else
1743
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1744
                                }
1745
                            }
1746
                        }
1747
                    }
1748
                }
1749

    
1750
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1751
                if (_lMConnector != null)
1752
                {
1753
                    _lMConnector.Commit();
1754
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
1755
                    bool bRemodelingStart = false;
1756
                    if (_LMSymbolStart != null)
1757
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
1758
                    bool bRemodelingEnd = false;
1759
                    if (_LMSymbolEnd != null)
1760
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
1761

    
1762
                    if (bRemodelingStart || bRemodelingEnd)
1763
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
1764

    
1765
                    FlowMarkModeling(groupLine);
1766
                    LineNumberModelingOnlyOne(groupLine);
1767

    
1768
                    ReleaseCOMObjects(_lMConnector);
1769
                }
1770
                else if (!isBranchModeling)
1771
                {
1772
                    Log.Write("Main Line Modeling : " + groupLine.UID);
1773
                }
1774

    
1775
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
1776
                x.ConnectedObject != null &&
1777
                x.ConnectedObject.GetType() == typeof(Line) &&
1778
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
1779
                .Select(x => x.ConnectedObject)
1780
                .ToList();
1781

    
1782
                foreach (var item in removeLines)
1783
                    RemoveLineForModeling(item as Line);
1784

    
1785
                if (_LMAItem != null)
1786
                    ReleaseCOMObjects(_LMAItem);
1787
                if (placeRunInputs != null)
1788
                    ReleaseCOMObjects(placeRunInputs);
1789
                if (_LMSymbolStart != null)
1790
                    ReleaseCOMObjects(_LMSymbolStart);
1791
                if (_LMSymbolEnd != null)
1792
                    ReleaseCOMObjects(_LMSymbolEnd);
1793

    
1794
                if (isBranchModeling && BranchLines.Contains(groupLine))
1795
                    BranchLines.Remove(groupLine);
1796
            }
1797
        }
1798

    
1799
        private void RemoveLineForModeling(Line line)
1800
        {
1801
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
1802
            if (modelItem != null)
1803
            {
1804
                foreach (LMRepresentation rep in modelItem.Representations)
1805
                {
1806
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
1807
                    {
1808
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
1809
                        dynamic OID = rep.get_GraphicOID().ToString();
1810
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1811
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1812
                        int verticesCount = lineStringGeometry.VertexCount;
1813
                        double[] vertices = null;
1814
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
1815
                        for (int i = 0; i < verticesCount; i++)
1816
                        {
1817
                            double x = 0;
1818
                            double y = 0;
1819
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
1820
                            if (verticesCount == 2 && (x < 0 || y < 0))
1821
                                _placement.PIDRemovePlacement(rep);
1822
                        }
1823
                        ReleaseCOMObjects(_LMConnector);
1824
                    }
1825
                }
1826

    
1827
                ReleaseCOMObjects(modelItem);
1828
            }
1829
        }
1830

    
1831
        private void GetConnectedLineGroup(Line line, List<Line> group)
1832
        {
1833
            if (!group.Contains(line))
1834
                group.Add(line);
1835
            foreach (var connector in line.CONNECTORS)
1836
            {
1837
                if (connector.ConnectedObject != null &&
1838
                    connector.ConnectedObject.GetType() == typeof(Line) &&
1839
                    !group.Contains(connector.ConnectedObject) &&
1840
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
1841
                {
1842
                    Line connLine = connector.ConnectedObject as Line;
1843
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
1844
                    {
1845
                        if (line.CONNECTORS.IndexOf(connector) == 0)
1846
                            group.Insert(0, connLine);
1847
                        else
1848
                            group.Add(connLine);
1849
                        GetConnectedLineGroup(connLine, group);
1850
                    }
1851
                }
1852
            }
1853
        }
1854

    
1855
        private void LineCoordinateCorrection(List<Line> group)
1856
        {
1857
            // 순서대로 전 Item 기준 정렬
1858
            LineCoordinateCorrectionByStart(group);
1859

    
1860
            // 역으로 심볼이 있을 경우 좌표 보정
1861
            LineCoordinateCorrectionForLastLine(group);
1862
        }
1863

    
1864
        private void LineCoordinateCorrectionByStart(List<Line> group)
1865
        {
1866
            for (int i = 0; i < group.Count; i++)
1867
            {
1868
                Line line = group[i];
1869
                if (i == 0)
1870
                {
1871
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1872
                    if (symbolConnector != null)
1873
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
1874
                }
1875
                else if (i != 0)
1876
                {
1877
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
1878
                }
1879
            }
1880
        }
1881

    
1882
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
1883
        {
1884
            Line checkLine = group[group.Count - 1];
1885
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1886
            if (lastSymbolConnector != null)
1887
            {
1888
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
1889
                for (int i = group.Count - 2; i >= 0; i--)
1890
                {
1891
                    Line line = group[i + 1];
1892
                    Line prevLine = group[i];
1893

    
1894
                    // 같으면 보정
1895
                    if (line.SlopeType == prevLine.SlopeType)
1896
                        LineCoordinateCorrectionByConnItem(prevLine, line);
1897
                    else
1898
                    {
1899
                        if (line.SlopeType == SlopeType.HORIZONTAL)
1900
                        {
1901
                            double prevX = 0;
1902
                            double prevY = 0;
1903
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1904
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
1905

    
1906
                            double x = 0;
1907
                            double y = 0;
1908
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1909
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
1910
                        }
1911
                        else if (line.SlopeType == SlopeType.VERTICAL)
1912
                        {
1913
                            double prevX = 0;
1914
                            double prevY = 0;
1915
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1916
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
1917

    
1918
                            double x = 0;
1919
                            double y = 0;
1920
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1921
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
1922
                        }
1923
                        break;
1924
                    }
1925
                }
1926
            }
1927
        }
1928

    
1929
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
1930
        {
1931
            double x = 0;
1932
            double y = 0;
1933
            if (connItem.GetType() == typeof(Symbol))
1934
            {
1935
                Symbol targetSymbol = connItem as Symbol;
1936
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
1937
                if (targetConnector != null)
1938
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
1939
                else
1940
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
1941
            }
1942
            else if (connItem.GetType() == typeof(Line))
1943
            {
1944
                Line targetLine = connItem as Line;
1945
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
1946
            }
1947

    
1948
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
1949
        }
1950

    
1951
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
1952
        {
1953
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1954
            int index = line.CONNECTORS.IndexOf(connector);
1955
            if (index == 0)
1956
            {
1957
                line.SPPID.START_X = x;
1958
                line.SPPID.START_Y = y;
1959
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1960
                    line.SPPID.END_Y = y;
1961
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1962
                    line.SPPID.END_X = x;
1963
            }
1964
            else
1965
            {
1966
                line.SPPID.END_X = x;
1967
                line.SPPID.END_Y = y;
1968
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1969
                    line.SPPID.START_Y = y;
1970
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1971
                    line.SPPID.START_X = x;
1972
            }
1973
        }
1974

    
1975
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
1976
        {
1977
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1978
            int index = line.CONNECTORS.IndexOf(connector);
1979
            if (index == 0)
1980
            {
1981
                line.SPPID.START_X = x;
1982
                if (line.SlopeType == SlopeType.VERTICAL)
1983
                    line.SPPID.END_X = x;
1984
            }
1985
            else
1986
            {
1987
                line.SPPID.END_X = x;
1988
                if (line.SlopeType == SlopeType.VERTICAL)
1989
                    line.SPPID.START_X = x;
1990
            }
1991
        }
1992

    
1993
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
1994
        {
1995
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1996
            int index = line.CONNECTORS.IndexOf(connector);
1997
            if (index == 0)
1998
            {
1999
                line.SPPID.START_Y = y;
2000
                if (line.SlopeType == SlopeType.HORIZONTAL)
2001
                    line.SPPID.END_Y = y;
2002
            }
2003
            else
2004
            {
2005
                line.SPPID.END_Y = y;
2006
                if (line.SlopeType == SlopeType.HORIZONTAL)
2007
                    line.SPPID.START_Y = y;
2008
            }
2009
        }
2010

    
2011
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2012
        {
2013
            if (symbol != null)
2014
            {
2015
                string repID = symbol.AsLMRepresentation().Id;
2016
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2017
                string lineUID = line.UID;
2018

    
2019
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2020
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2021
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2022

    
2023
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2024
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2025
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2026

    
2027
                if (startSpecBreak != null || startEndBreak != null)
2028
                    result = true;
2029
            }
2030
        }
2031

    
2032
        /// <summary>
2033
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2034
        /// </summary>
2035
        /// <param name="lines"></param>
2036
        /// <param name="prevLMConnector"></param>
2037
        /// <param name="startSymbol"></param>
2038
        /// <param name="endSymbol"></param>
2039
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2040
        {
2041
            string symbolPath = string.Empty;
2042
            #region get symbol path
2043
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2044
            symbolPath = GetSPPIDFileName(modelItem);
2045
            ReleaseCOMObjects(modelItem);
2046
            #endregion
2047
            bool diagonal = false;
2048
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2049
                diagonal = true;
2050
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2051
            LMConnector newConnector = null;
2052
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2053
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2054
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2055
            int verticesCount = lineStringGeometry.VertexCount;
2056
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2057

    
2058
            List<double[]> vertices = new List<double[]>();
2059
            for (int i = 1; i <= verticesCount; i++)
2060
            {
2061
                double x = 0;
2062
                double y = 0;
2063
                lineStringGeometry.GetVertex(i, ref x, ref y);
2064
                vertices.Add(new double[] { x, y });
2065
            }
2066

    
2067
            for (int i = 0; i < vertices.Count; i++)
2068
            {
2069
                double[] points = vertices[i];
2070
                // 시작 심볼이 있고 첫번째 좌표일 때
2071
                if (startSymbol != null && i == 0)
2072
                {
2073
                    if (bStart)
2074
                    {
2075
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2076
                        if (slopeType == SlopeType.HORIZONTAL)
2077
                            placeRunInputs.AddPoint(points[0], -0.1);
2078
                        else if (slopeType == SlopeType.VERTICAL)
2079
                            placeRunInputs.AddPoint(-0.1, points[1]);
2080
                        else
2081
                            placeRunInputs.AddPoint(points[0], -0.1);
2082

    
2083
                        placeRunInputs.AddPoint(points[0], points[1]);
2084
                    }
2085
                    else
2086
                    {
2087
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2088
                    }
2089
                }
2090
                // 마지막 심볼이 있고 마지막 좌표일 때
2091
                else if (endSymbol != null && i == vertices.Count - 1)
2092
                {
2093
                    if (bEnd)
2094
                    {
2095
                        placeRunInputs.AddPoint(points[0], points[1]);
2096

    
2097
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2098
                        if (slopeType == SlopeType.HORIZONTAL)
2099
                            placeRunInputs.AddPoint(points[0], -0.1);
2100
                        else if (slopeType == SlopeType.VERTICAL)
2101
                            placeRunInputs.AddPoint(-0.1, points[1]);
2102
                        else
2103
                            placeRunInputs.AddPoint(points[0], -0.1);
2104
                    }
2105
                    else
2106
                    {
2107
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2108
                    }
2109
                }
2110
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2111
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2112
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2113
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2114
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2115
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2116
                else
2117
                    placeRunInputs.AddPoint(points[0], points[1]);
2118
            }
2119

    
2120
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2121
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2122

    
2123
            ReleaseCOMObjects(placeRunInputs);
2124
            ReleaseCOMObjects(_LMAItem);
2125
            ReleaseCOMObjects(modelItem);
2126

    
2127
            if (newConnector != null)
2128
            {
2129
                newConnector.Commit();
2130
                if (startSymbol != null && bStart)
2131
                {
2132
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2133
                    placeRunInputs = new PlaceRunInputs();
2134
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2135
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2136
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2137
                    if (_LMConnector != null)
2138
                    {
2139
                        _LMConnector.Commit();
2140
                        RemoveConnectorForReModelingLine(newConnector);
2141
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2142
                        ReleaseCOMObjects(_LMConnector);
2143
                    }
2144
                    ReleaseCOMObjects(placeRunInputs);
2145
                    ReleaseCOMObjects(_LMAItem);
2146
                }
2147

    
2148
                if (endSymbol != null && bEnd)
2149
                {
2150
                    if (startSymbol != null)
2151
                    {
2152
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2153
                        newConnector = dicVertices.First().Key;
2154
                    }
2155

    
2156
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2157
                    placeRunInputs = new PlaceRunInputs();
2158
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2159
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2160
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2161
                    if (_LMConnector != null)
2162
                    {
2163
                        _LMConnector.Commit();
2164
                        RemoveConnectorForReModelingLine(newConnector);
2165
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2166
                        ReleaseCOMObjects(_LMConnector);
2167
                    }
2168
                    ReleaseCOMObjects(placeRunInputs);
2169
                    ReleaseCOMObjects(_LMAItem);
2170
                }
2171

    
2172
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2173
                ReleaseCOMObjects(newConnector);
2174
            }
2175

    
2176
            ReleaseCOMObjects(modelItem);
2177
        }
2178

    
2179
        /// <summary>
2180
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2181
        /// </summary>
2182
        /// <param name="connector"></param>
2183
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2184
        {
2185
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2186
            foreach (var item in dicVertices)
2187
            {
2188
                if (item.Value.Count == 2)
2189
                {
2190
                    bool result = false;
2191
                    foreach (var point in item.Value)
2192
                    {
2193
                        if (point[0] < 0 || point[1] < 0)
2194
                        {
2195
                            result = true;
2196
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2197
                            break;
2198
                        }
2199
                    }
2200

    
2201
                    if (result)
2202
                        break;
2203
                }
2204
            }
2205
            foreach (var item in dicVertices)
2206
                ReleaseCOMObjects(item.Key);
2207
        }
2208

    
2209
        /// <summary>
2210
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2211
        /// </summary>
2212
        /// <param name="symbol"></param>
2213
        /// <param name="line"></param>
2214
        /// <returns></returns>
2215
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2216
        {
2217
            LMSymbol _LMSymbol = null;
2218
            foreach (var connector in symbol.CONNECTORS)
2219
            {
2220
                if (connector.CONNECTEDITEM == line.UID)
2221
                {
2222
                    if (connector.Index == 0)
2223
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2224
                    else
2225
                    {
2226
                        ChildSymbol child = null;
2227
                        foreach (var childSymbol in symbol.ChildSymbols)
2228
                        {
2229
                            if (childSymbol.Connectors.Contains(connector))
2230
                                child = childSymbol;
2231
                            else
2232
                                child = GetChildSymbolByConnector(childSymbol, connector);
2233

    
2234
                            if (child != null)
2235
                                break;
2236
                        }
2237

    
2238
                        if (child != null)
2239
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2240
                    }
2241

    
2242
                    break;
2243
                }
2244
            }
2245

    
2246
            return _LMSymbol;
2247
        }
2248

    
2249
        /// <summary>
2250
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2251
        /// </summary>
2252
        /// <param name="item"></param>
2253
        /// <param name="connector"></param>
2254
        /// <returns></returns>
2255
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2256
        {
2257
            foreach (var childSymbol in item.ChildSymbols)
2258
            {
2259
                if (childSymbol.Connectors.Contains(connector))
2260
                    return childSymbol;
2261
                else
2262
                    return GetChildSymbolByConnector(childSymbol, connector);
2263
            }
2264

    
2265
            return null;
2266
        }
2267

    
2268
        /// <summary>
2269
        /// EndBreak 모델링 메서드
2270
        /// </summary>
2271
        /// <param name="endBreak"></param>
2272
        private void EndBreakModeling(EndBreak endBreak)
2273
        {
2274
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2275
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2276
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2277

    
2278
            if (targetLMConnector != null)
2279
            {
2280
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2281
                Array array = null;
2282
                if (point != null)
2283
                    array = new double[] { 0, point[0], point[1] };
2284
                else
2285
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2286
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2287
                if (_LmLabelPersist != null)
2288
                {
2289
                    _LmLabelPersist.Commit();
2290
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2291
                    if (_LmLabelPersist.ModelItemObject != null)
2292
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2293
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2294
                    ReleaseCOMObjects(_LmLabelPersist);
2295
                }
2296
                ReleaseCOMObjects(targetLMConnector);
2297
            }
2298
        }
2299

    
2300
        private LMConnector ReModelingLMConnector(LMConnector connector, string changeSymbolPath = null)
2301
        {
2302
            string symbolPath = string.Empty;
2303
            #region get symbol path
2304
            if (string.IsNullOrEmpty(changeSymbolPath))
2305
            {
2306
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2307
                symbolPath = GetSPPIDFileName(modelItem);
2308
                ReleaseCOMObjects(modelItem);
2309
            }
2310
            else
2311
                symbolPath = changeSymbolPath;
2312
            
2313
            #endregion
2314

    
2315
            LMConnector newConnector = null;
2316
            dynamic OID = connector.get_GraphicOID().ToString();
2317
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2318
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2319
            int verticesCount = lineStringGeometry.VertexCount;
2320
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2321
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2322

    
2323
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2324
            {
2325
                double[] vertices = null;
2326
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2327
                double x = 0;
2328
                double y = 0;
2329
                lineStringGeometry.GetVertex(1, ref x, ref y);
2330

    
2331
                string flowDirection = string.Empty;
2332
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2333
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2334
                    flowDirection = flowAttribute.get_Value().ToString();
2335

    
2336
                if (flowDirection == "End 1 is downstream (Outlet)")
2337
                {
2338
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2339
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2340
                    flowDirection = "End 1 is upstream (Inlet)";
2341
                }
2342
                else
2343
                {
2344
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2345
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2346
                }
2347

    
2348
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2349
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2350
                newConnector.Commit();
2351
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2352
                if (!string.IsNullOrEmpty(flowDirection))
2353
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2354
            }
2355
            else
2356
            {
2357
                List<double[]> vertices = new List<double[]>();
2358
                for (int i = 1; i <= verticesCount; i++)
2359
                {
2360
                    double x = 0;
2361
                    double y = 0;
2362
                    lineStringGeometry.GetVertex(i, ref x, ref y);
2363
                    vertices.Add(new double[] { x, y });
2364
                }
2365

    
2366
                for (int i = 0; i < vertices.Count; i++)
2367
                {
2368
                    double[] points = vertices[i];
2369
                    if (i == 0)
2370
                    {
2371
                        if (connector.ConnectItem1SymbolObject != null)
2372
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, points[0], points[1]);
2373
                        else
2374
                            placeRunInputs.AddPoint(points[0], points[1]);
2375
                    }
2376
                    else if (i == vertices.Count - 1)
2377
                    {
2378
                        if (connector.ConnectItem2SymbolObject != null)
2379
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, points[0], points[1]);
2380
                        else
2381
                            placeRunInputs.AddPoint(points[0], points[1]);
2382
                    }
2383
                    else
2384
                        placeRunInputs.AddPoint(points[0], points[1]);
2385
                }
2386

    
2387
                List<Line> lines = SPPIDUtil.FindLinesByModelId(document, connector.ModelItemID);
2388

    
2389
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2390
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2391
                newConnector.Commit();
2392
                foreach (var line in lines)
2393
                    line.SPPID.ModelItemId = newConnector.ModelItemID;
2394
            }
2395

    
2396

    
2397
            return newConnector;
2398
        }
2399

    
2400
        /// <summary>
2401
        /// SpecBreak Modeling 메서드
2402
        /// </summary>
2403
        /// <param name="specBreak"></param>
2404
        private void SpecBreakModeling(SpecBreak specBreak)
2405
        {
2406
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2407
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2408

    
2409
            if (upStreamObj != null &&
2410
                downStreamObj != null)
2411
            {
2412
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2413

    
2414
                if (targetLMConnector != null)
2415
                {
2416
                    foreach (var attribute in specBreak.ATTRIBUTES)
2417
                    {
2418
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2419
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2420
                        {
2421
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2422
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2423
                            Array array = null;
2424
                            if (point != null)
2425
                                array = new double[] { 0, point[0], point[1] };
2426
                            else
2427
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2428
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2429

    
2430
                            if (_LmLabelPersist != null)
2431
                            {
2432
                                _LmLabelPersist.Commit();
2433
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2434
                                if (_LmLabelPersist.ModelItemObject != null)
2435
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2436
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2437
                                ReleaseCOMObjects(_LmLabelPersist);
2438
                            }
2439
                        }
2440
                    }
2441
                    ReleaseCOMObjects(targetLMConnector);
2442
                }
2443
            }
2444
        }
2445

    
2446
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2447
        {
2448
            LMConnector targetConnector = null;
2449
            Symbol targetSymbol = targetObj as Symbol;
2450
            Symbol connectedSymbol = connectedObj as Symbol;
2451
            Line targetLine = targetObj as Line;
2452
            Line connectedLine = connectedObj as Line;
2453
            if (targetSymbol != null && connectedSymbol != null)
2454
            {
2455
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2456
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2457

    
2458
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2459
                {
2460
                    if (connector.get_ItemStatus() != "Active")
2461
                        continue;
2462

    
2463
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2464
                    {
2465
                        targetConnector = connector;
2466
                        break;
2467
                    }
2468
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2469
                    {
2470
                        targetConnector = connector;
2471
                        break;
2472
                    }
2473
                }
2474

    
2475
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2476
                {
2477
                    if (connector.get_ItemStatus() != "Active")
2478
                        continue;
2479

    
2480
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2481
                    {
2482
                        targetConnector = connector;
2483
                        break;
2484
                    }
2485
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2486
                    {
2487
                        targetConnector = connector;
2488
                        break;
2489
                    }
2490
                }
2491

    
2492
                ReleaseCOMObjects(targetLMSymbol);
2493
                ReleaseCOMObjects(connectedLMSymbol);
2494
            }
2495
            else if (targetLine != null && connectedLine != null)
2496
            {
2497
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2498
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2499

    
2500
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2501
                {
2502
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2503
                    {
2504
                        if (targetConnector != null)
2505
                            break;
2506

    
2507
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2508
                        {
2509
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2510

    
2511
                            if (IsConnected(_LMConnector, connectedModelItem))
2512
                                targetConnector = _LMConnector;
2513
                            else
2514
                                ReleaseCOMObjects(_LMConnector);
2515
                        }
2516
                    }
2517

    
2518
                    ReleaseCOMObjects(targetModelItem);
2519
                }
2520
            }
2521
            else
2522
            {
2523
                LMSymbol connectedLMSymbol = null;
2524
                if (connectedSymbol != null)
2525
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2526
                else if (targetSymbol != null)
2527
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2528
                else
2529
                {
2530

    
2531
                }
2532
                LMModelItem targetModelItem = null;
2533
                if (targetLine != null)
2534
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2535
                else if (connectedLine != null)
2536
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2537
                else
2538
                {
2539

    
2540
                }
2541
                if (connectedLMSymbol != null && targetModelItem != null)
2542
                {
2543
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2544
                    {
2545
                        if (connector.get_ItemStatus() != "Active")
2546
                            continue;
2547

    
2548
                        if (IsConnected(connector, targetModelItem))
2549
                        {
2550
                            targetConnector = connector;
2551
                            break;
2552
                        }
2553
                    }
2554

    
2555
                    if (targetConnector == null)
2556
                    {
2557
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2558
                        {
2559
                            if (connector.get_ItemStatus() != "Active")
2560
                                continue;
2561

    
2562
                            if (IsConnected(connector, targetModelItem))
2563
                            {
2564
                                targetConnector = connector;
2565
                                break;
2566
                            }
2567
                        }
2568
                    }
2569
                }
2570

    
2571
            }
2572

    
2573
            return targetConnector;
2574
        }
2575

    
2576
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2577
        {
2578
            double[] result = null;
2579
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2580
            {
2581
                return GetConnectorVertices(targetConnector)[0];
2582
            }
2583
            else
2584
            {
2585
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
2586
                {
2587
                    Line line = connObj as Line;
2588
                    LMConnector connectedConnector = null;
2589
                    int connIndex = 0;
2590
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2591
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
2592

    
2593
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
2594

    
2595
                    ReleaseCOMObjects(modelItem);
2596
                    ReleaseCOMObjects(connectedConnector);
2597

    
2598
                    if (vertices.Count > 0)
2599
                    {
2600
                        if (connIndex == 1)
2601
                            return vertices[0];
2602
                        else if (connIndex == 2)
2603
                            return vertices[vertices.Count - 1];
2604
                    }
2605
                }
2606
                else
2607
                {
2608
                    Log.Write("error in GetSegemtPoint");
2609
                }
2610
            }
2611

    
2612
            return result;
2613
        }
2614

    
2615
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
2616
        {
2617
            bool result = false;
2618

    
2619
            foreach (LMRepresentation rep in modelItem.Representations)
2620
            {
2621
                if (result)
2622
                    break;
2623

    
2624
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2625
                {
2626
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2627

    
2628
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2629
                        connector.ConnectItem1SymbolObject != null &&
2630
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2631
                    {
2632
                        result = true;
2633
                        ReleaseCOMObjects(_LMConnector);
2634
                        break;
2635
                    }
2636
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2637
                        connector.ConnectItem2SymbolObject != null &&
2638
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2639
                    {
2640
                        result = true;
2641
                        ReleaseCOMObjects(_LMConnector);
2642
                        break;
2643
                    }
2644
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2645
                        connector.ConnectItem1SymbolObject != null &&
2646
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2647
                    {
2648
                        result = true;
2649
                        ReleaseCOMObjects(_LMConnector);
2650
                        break;
2651
                    }
2652
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2653
                        connector.ConnectItem2SymbolObject != null &&
2654
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2655
                    {
2656
                        result = true;
2657
                        ReleaseCOMObjects(_LMConnector);
2658
                        break;
2659
                    }
2660

    
2661
                    ReleaseCOMObjects(_LMConnector);
2662
                }
2663
            }
2664

    
2665

    
2666
            return result;
2667
        }
2668

    
2669
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
2670
        {
2671
            foreach (LMRepresentation rep in modelItem.Representations)
2672
            {
2673
                if (connectedConnector != null)
2674
                    break;
2675

    
2676
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2677
                {
2678
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2679

    
2680
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2681
                        connector.ConnectItem1SymbolObject != null &&
2682
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2683
                    {
2684
                        connectedConnector = _LMConnector;
2685
                        connectorIndex = 1;
2686
                        break;
2687
                    }
2688
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2689
                        connector.ConnectItem2SymbolObject != null &&
2690
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2691
                    {
2692
                        connectedConnector = _LMConnector;
2693
                        connectorIndex = 2;
2694
                        break;
2695
                    }
2696
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2697
                        connector.ConnectItem1SymbolObject != null &&
2698
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2699
                    {
2700
                        connectedConnector = _LMConnector;
2701
                        connectorIndex = 1;
2702
                        break;
2703
                    }
2704
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2705
                        connector.ConnectItem2SymbolObject != null &&
2706
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2707
                    {
2708
                        connectedConnector = _LMConnector;
2709
                        connectorIndex = 2;
2710
                        break;
2711
                    }
2712

    
2713
                    if (connectedConnector == null)
2714
                        ReleaseCOMObjects(_LMConnector);
2715
                }
2716
            }
2717
        }
2718

    
2719
        /// <summary>
2720
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
2721
        /// </summary>
2722
        /// <param name="modelItemID1"></param>
2723
        /// <param name="modelItemID2"></param>
2724
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
2725
        {
2726
            try
2727
            {
2728
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
2729
                _LMAItem item1 = modelItem1.AsLMAItem();
2730
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
2731
                _LMAItem item2 = modelItem2.AsLMAItem();
2732

    
2733
                // item2가 item1으로 조인
2734
                _placement.PIDJoinRuns(ref item1, ref item2);
2735
                item1.Commit();
2736
                item2.Commit();
2737

    
2738
                string beforeID = string.Empty;
2739
                string afterID = string.Empty;
2740

    
2741
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
2742
                {
2743
                    beforeID = modelItem2.Id;
2744
                    afterID = modelItem1.Id;
2745
                    survivorId = afterID;
2746
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
2747
                    if (attribute != null)
2748
                        attribute.set_Value("End 1 is upstream (Inlet)");
2749
                }
2750
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
2751
                {
2752
                    beforeID = modelItem1.Id;
2753
                    afterID = modelItem2.Id;
2754
                    survivorId = afterID;
2755
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
2756
                    if (attribute != null)
2757
                        attribute.set_Value("End 1 is upstream (Inlet)");
2758
                }
2759
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
2760
                    survivorId = null;
2761
                else
2762
                {
2763
                    Log.Write("잘못된 경우");
2764
                    survivorId = null;
2765
                }
2766

    
2767
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
2768
                {
2769
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
2770
                    foreach (var line in lines)
2771
                        line.SPPID.ModelItemId = afterID;
2772
                }
2773

    
2774
                ReleaseCOMObjects(modelItem1);
2775
                ReleaseCOMObjects(item1);
2776
                ReleaseCOMObjects(modelItem2);
2777
                ReleaseCOMObjects(item2);
2778
            }
2779
            catch (Exception ex)
2780
            {
2781
                Log.Write("Join Error");
2782
                Log.Write(ex.Message);
2783
            }
2784
        }
2785

    
2786
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
2787
        {
2788
            List<string> modelItemIDs = new List<string>();
2789
            foreach (LMConnector connector in symbol.Avoid1Connectors)
2790
            {
2791
                LMModelItem modelItem = connector.ModelItemObject;
2792
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2793
                    modelItemIDs.Add(modelItem.Id);
2794
                ReleaseCOMObjects(modelItem);
2795
                ReleaseCOMObjects(connector);
2796
            }
2797

    
2798
            foreach (LMConnector connector in symbol.Avoid2Connectors)
2799
            {
2800
                LMModelItem modelItem = connector.ModelItemObject;
2801
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2802
                    modelItemIDs.Add(modelItem.Id);
2803
                ReleaseCOMObjects(modelItem);
2804
                ReleaseCOMObjects(connector);
2805
            }
2806

    
2807

    
2808
            List<string> result = new List<string>();
2809
            modelItemIDs = modelItemIDs.Distinct().ToList();
2810
            string originalName = GetSPPIDFileName(modelId);
2811
            bool existZeroLength = false;
2812
            foreach (var item in modelItemIDs)
2813
            {
2814
                string fileName = GetSPPIDFileName(item);
2815
                if (originalName == fileName)
2816
                    result.Add(item);
2817
                else
2818
                {
2819
                    LMConnector connector = GetLMConnectorOnlyOne(item);
2820
                    if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()) && connector.LabelPersists.Count == 0)
2821
                    {
2822
                        result.Add(item);
2823
                        ReleaseCOMObjects(connector);
2824
                        existZeroLength = true;
2825
                    }
2826
                }
2827
            }
2828

    
2829
            if (result.Count == 1 && existZeroLength)
2830
            {
2831
                LMConnector connector = GetLMConnectorOnlyOne(result[0]);
2832
                LMConnector newConnector = ReModelingLMConnector(connector, originalName);
2833
                result.Clear();
2834
                if (newConnector != null)
2835
                    result.Add(newConnector.ModelItemID);
2836

    
2837
                ReleaseCOMObjects(connector);
2838
                connector = null;
2839
                ReleaseCOMObjects(newConnector);
2840
                newConnector = null;
2841
            }
2842
            
2843
            return result;
2844
        }
2845

    
2846
        /// <summary>
2847
        /// PipeRun의 좌표를 가져오는 메서드
2848
        /// </summary>
2849
        /// <param name="modelId"></param>
2850
        /// <returns></returns>
2851
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId)
2852
        {
2853
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
2854
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
2855

    
2856
            if (modelItem != null)
2857
            {
2858
                foreach (LMRepresentation rep in modelItem.Representations)
2859
                {
2860
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2861
                    {
2862
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2863
                        connectorVertices.Add(_LMConnector, new List<double[]>());
2864
                        dynamic OID = rep.get_GraphicOID().ToString();
2865
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2866
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2867
                        int verticesCount = lineStringGeometry.VertexCount;
2868
                        double[] vertices = null;
2869
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2870
                        for (int i = 0; i < verticesCount; i++)
2871
                        {
2872
                            double x = 0;
2873
                            double y = 0;
2874
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2875
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
2876
                        }
2877
                    }
2878
                }
2879

    
2880
                ReleaseCOMObjects(modelItem);
2881
            }
2882

    
2883
            return connectorVertices;
2884
        }
2885

    
2886
        private List<double[]> GetConnectorVertices(LMConnector connector)
2887
        {
2888
            List<double[]> vertices = new List<double[]>();
2889
            if (connector != null)
2890
            {
2891
                dynamic OID = connector.get_GraphicOID().ToString();
2892
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2893
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2894
                int verticesCount = lineStringGeometry.VertexCount;
2895
                double[] value = null;
2896
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
2897
                for (int i = 0; i < verticesCount; i++)
2898
                {
2899
                    double x = 0;
2900
                    double y = 0;
2901
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2902
                    vertices.Add(new double[] { x, y });
2903
                }
2904
            }
2905
            return vertices;
2906
        }
2907

    
2908
        /// <summary>
2909
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
2910
        /// </summary>
2911
        /// <param name="connectorVertices"></param>
2912
        /// <param name="connX"></param>
2913
        /// <param name="connY"></param>
2914
        /// <returns></returns>
2915
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
2916
        {
2917
            double length = double.MaxValue;
2918
            LMConnector targetConnector = null;
2919
            foreach (var item in connectorVertices)
2920
            {
2921
                List<double[]> points = item.Value;
2922
                for (int i = 0; i < points.Count - 1; i++)
2923
                {
2924
                    double[] point1 = points[i];
2925
                    double[] point2 = points[i + 1];
2926
                    double x1 = Math.Min(point1[0], point2[0]);
2927
                    double y1 = Math.Min(point1[1], point2[1]);
2928
                    double x2 = Math.Max(point1[0], point2[0]);
2929
                    double y2 = Math.Max(point1[1], point2[1]);
2930

    
2931
                    if ((x1 <= connX && x2 >= connX) ||
2932
                        (y1 <= connY && y2 >= connY))
2933
                    {
2934
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
2935
                        if (length >= distance)
2936
                        {
2937
                            targetConnector = item.Key;
2938
                            length = distance;
2939
                        }
2940

    
2941
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
2942
                        if (length >= distance)
2943
                        {
2944
                            targetConnector = item.Key;
2945
                            length = distance;
2946
                        }
2947
                    }
2948
                }
2949
            }
2950

    
2951
            // 못찾았을때.
2952
            length = double.MaxValue;
2953
            if (targetConnector == null)
2954
            {
2955
                foreach (var item in connectorVertices)
2956
                {
2957
                    List<double[]> points = item.Value;
2958

    
2959
                    foreach (double[] point in points)
2960
                    {
2961
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
2962
                        if (length >= distance)
2963
                        {
2964
                            targetConnector = item.Key;
2965
                            length = distance;
2966
                        }
2967
                    }
2968
                }
2969
            }
2970

    
2971
            return targetConnector;
2972
        }
2973

    
2974
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
2975
        {
2976
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
2977
            if (vertices.Count == 0)
2978
                return null;
2979

    
2980
            double length = double.MaxValue;
2981
            LMConnector targetConnector = null;
2982
            double[] resultPoint = null;
2983
            List<double[]> targetVertices = null;
2984

    
2985
            // Vertices 포인트에 제일 가까운곳
2986
            foreach (var item in vertices)
2987
            {
2988
                List<double[]> points = item.Value;
2989
                for (int i = 0; i < points.Count; i++)
2990
                {
2991
                    double[] point = points[i];
2992
                    double tempX = point[0];
2993
                    double tempY = point[1];
2994

    
2995
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
2996
                    if (length >= distance)
2997
                    {
2998
                        targetConnector = item.Key;
2999
                        length = distance;
3000
                        resultPoint = point;
3001
                        targetVertices = item.Value;
3002
                    }
3003
                }
3004
            }
3005

    
3006
            // Vertices Cross에 제일 가까운곳
3007
            foreach (var item in vertices)
3008
            {
3009
                List<double[]> points = item.Value;
3010
                for (int i = 0; i < points.Count - 1; i++)
3011
                {
3012
                    double[] point1 = points[i];
3013
                    double[] point2 = points[i + 1];
3014

    
3015
                    double maxLineX = Math.Max(point1[0], point2[0]);
3016
                    double minLineX = Math.Min(point1[0], point2[0]);
3017
                    double maxLineY = Math.Max(point1[1], point2[1]);
3018
                    double minLineY = Math.Min(point1[1], point2[1]);
3019

    
3020
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3021

    
3022
                    double[] crossingPoint = SPPIDUtil.CalcLineCrossingPoint(line.SPPID.START_X, line.SPPID.START_Y, line.SPPID.END_X, line.SPPID.END_Y, point1[0], point1[1], point2[0], point2[1]);
3023
                    if (crossingPoint != null)
3024
                    {
3025
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3026
                        if (length >= distance)
3027
                        {
3028
                            if (slope == SlopeType.Slope &&
3029
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3030
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3031
                            {
3032
                                targetConnector = item.Key;
3033
                                length = distance;
3034
                                resultPoint = crossingPoint;
3035
                                targetVertices = item.Value;
3036
                            }
3037
                            else if (slope == SlopeType.HORIZONTAL &&
3038
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3039
                            {
3040
                                targetConnector = item.Key;
3041
                                length = distance;
3042
                                resultPoint = crossingPoint;
3043
                                targetVertices = item.Value;
3044
                            }
3045
                            else if (slope == SlopeType.VERTICAL &&
3046
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3047
                            {
3048
                                targetConnector = item.Key;
3049
                                length = distance;
3050
                                resultPoint = crossingPoint;
3051
                                targetVertices = item.Value;
3052
                            }
3053
                        }
3054
                    }
3055
                }
3056
            }
3057

    
3058
            foreach (var item in vertices)
3059
                if (item.Key != null && item.Key != targetConnector)
3060
                    ReleaseCOMObjects(item.Key);
3061

    
3062
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3063
            {
3064
                double tempResultX = resultPoint[0];
3065
                double tempResultY = resultPoint[1];
3066
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3067

    
3068
                GridSetting gridSetting = GridSetting.GetInstance();
3069

    
3070
                for (int i = 0; i < targetVertices.Count; i++)
3071
                {
3072
                    double[] point = targetVertices[i];
3073
                    double tempX = targetVertices[i][0];
3074
                    double tempY = targetVertices[i][1];
3075
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3076
                    if (tempX == tempResultX && tempY == tempResultY)
3077
                    {
3078
                        if (i == 0)
3079
                        {
3080
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3081
                            bool containZeroLength = false;
3082
                            if (connSymbol != null)
3083
                            {
3084
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3085
                                {
3086
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3087
                                        containZeroLength = true;
3088
                                }
3089
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3090
                                {
3091
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3092
                                        containZeroLength = true;
3093
                                }
3094
                            }
3095

    
3096
                            if (connSymbol == null ||
3097
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3098
                                containZeroLength)
3099
                            {
3100
                                bool bCalcX = false;
3101
                                bool bCalcY = false;
3102
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3103
                                    bCalcX = true;
3104
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3105
                                    bCalcY = true;
3106
                                else
3107
                                {
3108
                                    bCalcX = true;
3109
                                    bCalcY = true;
3110
                                }
3111

    
3112
                                if (bCalcX)
3113
                                {
3114
                                    double nextX = targetVertices[i + 1][0];
3115
                                    double newX = 0;
3116
                                    if (nextX > tempX)
3117
                                    {
3118
                                        newX = tempX + gridSetting.Length;
3119
                                        if (newX > nextX)
3120
                                            newX = (point[0] + nextX) / 2;
3121
                                    }
3122
                                    else
3123
                                    {
3124
                                        newX = tempX - gridSetting.Length;
3125
                                        if (newX < nextX)
3126
                                            newX = (point[0] + nextX) / 2;
3127
                                    }
3128
                                    resultPoint = new double[] { newX, resultPoint[1] };
3129
                                }
3130

    
3131
                                if (bCalcY)
3132
                                {
3133
                                    double nextY = targetVertices[i + 1][1];
3134
                                    double newY = 0;
3135
                                    if (nextY > tempY)
3136
                                    {
3137
                                        newY = tempY + gridSetting.Length;
3138
                                        if (newY > nextY)
3139
                                            newY = (point[1] + nextY) / 2;
3140
                                    }
3141
                                    else
3142
                                    {
3143
                                        newY = tempY - gridSetting.Length;
3144
                                        if (newY < nextY)
3145
                                            newY = (point[1] + nextY) / 2;
3146
                                    }
3147
                                    resultPoint = new double[] { resultPoint[0], newY };
3148
                                }
3149
                            }
3150
                        }
3151
                        else if (i == targetVertices.Count - 1)
3152
                        {
3153
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3154
                            bool containZeroLength = false;
3155
                            if (connSymbol != null)
3156
                            {
3157
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3158
                                {
3159
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3160
                                        containZeroLength = true;
3161
                                }
3162
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3163
                                {
3164
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3165
                                        containZeroLength = true;
3166
                                }
3167
                            }
3168

    
3169
                            if (connSymbol == null ||
3170
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3171
                                containZeroLength)
3172
                            {
3173
                                bool bCalcX = false;
3174
                                bool bCalcY = false;
3175
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3176
                                    bCalcX = true;
3177
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3178
                                    bCalcY = true;
3179
                                else
3180
                                {
3181
                                    bCalcX = true;
3182
                                    bCalcY = true;
3183
                                }
3184

    
3185
                                if (bCalcX)
3186
                                {
3187
                                    double nextX = targetVertices[i - 1][0];
3188
                                    double newX = 0;
3189
                                    if (nextX > tempX)
3190
                                    {
3191
                                        newX = tempX + gridSetting.Length;
3192
                                        if (newX > nextX)
3193
                                            newX = (point[0] + nextX) / 2;
3194
                                    }
3195
                                    else
3196
                                    {
3197
                                        newX = tempX - gridSetting.Length;
3198
                                        if (newX < nextX)
3199
                                            newX = (point[0] + nextX) / 2;
3200
                                    }
3201
                                    resultPoint = new double[] { newX, resultPoint[1] };
3202
                                }
3203

    
3204
                                if (bCalcY)
3205
                                {
3206
                                    double nextY = targetVertices[i - 1][1];
3207
                                    double newY = 0;
3208
                                    if (nextY > tempY)
3209
                                    {
3210
                                        newY = tempY + gridSetting.Length;
3211
                                        if (newY > nextY)
3212
                                            newY = (point[1] + nextY) / 2;
3213
                                    }
3214
                                    else
3215
                                    {
3216
                                        newY = tempY - gridSetting.Length;
3217
                                        if (newY < nextY)
3218
                                            newY = (point[1] + nextY) / 2;
3219
                                    }
3220
                                    resultPoint = new double[] { resultPoint[0], newY };
3221
                                }
3222
                            }
3223
                        }
3224
                        break;
3225
                    }
3226
                }
3227
            }
3228

    
3229
            x = resultPoint[0];
3230
            y = resultPoint[1];
3231

    
3232
            return targetConnector;
3233
        }
3234

    
3235
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3236
        {
3237
            LMConnector result = null;
3238
            List<LMConnector> connectors = new List<LMConnector>();
3239
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3240

    
3241
            if (modelItem != null)
3242
            {
3243
                foreach (LMRepresentation rep in modelItem.Representations)
3244
                {
3245
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3246
                        connectors.Add(dataSource.GetConnector(rep.Id));
3247
                }
3248

    
3249
                ReleaseCOMObjects(modelItem);
3250
            }
3251

    
3252
            if (connectors.Count == 1)
3253
                result = connectors[0];
3254
            else
3255
                foreach (var item in connectors)
3256
                    ReleaseCOMObjects(item);
3257

    
3258
            return result;
3259
        }
3260

    
3261
        /// <summary>
3262
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3263
        /// </summary>
3264
        /// <param name="lineNumber"></param>
3265
        private void LineNumberModelingOnlyOne(Line line)
3266
        {
3267
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3268
            if (lineNumber != null)
3269
            {
3270
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3271
                if (connectedLMConnector != null)
3272
                {
3273
                    double x = 0;
3274
                    double y = 0;
3275
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3276

    
3277
                    Array points = new double[] { 0, x, y };
3278
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3279

    
3280
                    if (_LmLabelPresist != null)
3281
                    {
3282
                        _LmLabelPresist.Commit();
3283
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3284
                        ReleaseCOMObjects(_LmLabelPresist);
3285
                    }
3286
                }
3287
            }
3288
        }
3289

    
3290
        private void LineNumberModeling(LineNumber lineNumber)
3291
        {
3292
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3293
            if (line != null)
3294
            {
3295
                double x = 0;
3296
                double y = 0;
3297
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3298

    
3299
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3300
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3301
                if (connectedLMConnector != null)
3302
                {
3303
                    Array points = new double[] { 0, x, y };
3304
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3305

    
3306
                    if (_LmLabelPresist != null)
3307
                    {
3308
                        _LmLabelPresist.Commit();
3309
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3310
                        ReleaseCOMObjects(_LmLabelPresist);
3311
                    }
3312
                }
3313

    
3314
                foreach (var item in connectorVertices)
3315
                    ReleaseCOMObjects(item.Key);
3316
            }
3317
        }
3318
        /// <summary>
3319
        /// Flow Mark Modeling
3320
        /// </summary>
3321
        /// <param name="line"></param>
3322
        private void FlowMarkModeling(Line line)
3323
        {
3324
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3325
            {
3326
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3327
                if (connector != null)
3328
                {
3329
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
3330
                    List<double[]> vertices = GetConnectorVertices(connector);
3331
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
3332
                    double[] point = vertices[vertices.Count - 1];
3333
                    Array array = new double[] { 0, point[0], point[1] };
3334
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
3335
                    if (_LMLabelPersist != null)
3336
                    {
3337
                        _LMLabelPersist.Commit();
3338
                        ReleaseCOMObjects(_LMLabelPersist);
3339
                    }
3340
                        
3341
                }
3342
            }
3343
        }
3344

    
3345
        /// <summary>
3346
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
3347
        /// </summary>
3348
        /// <param name="lineNumber"></param>
3349
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
3350
        {
3351
            foreach (LineRun run in lineNumber.RUNS)
3352
            {
3353
                foreach (var item in run.RUNITEMS)
3354
                {
3355
                    if (item.GetType() == typeof(Symbol))
3356
                    {
3357
                        Symbol symbol = item as Symbol;
3358
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3359
                        if (_LMSymbol != null)
3360
                        {
3361
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3362

    
3363
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3364
                            {
3365
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3366
                                {
3367
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3368
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3369
                                    {
3370
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3371
                                        if (_LMAAttribute != null)
3372
                                        {
3373
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3374
                                                _LMAAttribute.set_Value(attribute.VALUE);
3375
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3376
                                                _LMAAttribute.set_Value(attribute.VALUE);
3377
                                        }
3378
                                    }
3379
                                }
3380
                                _LMModelItem.Commit();
3381
                            }
3382
                            if (_LMModelItem != null)
3383
                                ReleaseCOMObjects(_LMModelItem);
3384
                        }
3385
                        if (_LMSymbol != null)
3386
                            ReleaseCOMObjects(_LMSymbol);
3387
                    }
3388
                    else if (item.GetType() == typeof(Line))
3389
                    {
3390
                        Line line = item as Line;
3391
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
3392
                        {
3393
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3394
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3395
                            {
3396
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3397
                                {
3398
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3399
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3400
                                    {
3401
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3402
                                        if (_LMAAttribute != null)
3403
                                        {
3404
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3405
                                                _LMAAttribute.set_Value(attribute.VALUE);
3406
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3407
                                                _LMAAttribute.set_Value(attribute.VALUE);
3408

    
3409
                                        }
3410
                                    }
3411
                                }
3412
                                _LMModelItem.Commit();
3413
                            }
3414
                            if (_LMModelItem != null)
3415
                                ReleaseCOMObjects(_LMModelItem);
3416
                            endLine.Add(line.SPPID.ModelItemId);
3417
                        }
3418
                    }
3419
                }
3420
            }
3421
        }
3422

    
3423
        /// <summary>
3424
        /// Symbol Attribute 입력 메서드
3425
        /// </summary>
3426
        /// <param name="item"></param>
3427
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
3428
        {
3429
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
3430
            string sRep = null;
3431
            if (targetItem.GetType() == typeof(Symbol))
3432
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
3433
            else if (targetItem.GetType() == typeof(Equipment))
3434
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
3435

    
3436
            if (!string.IsNullOrEmpty(sRep))
3437
            {
3438
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
3439
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3440
                LMAAttributes _Attributes = _LMModelItem.Attributes;
3441
                
3442
                foreach (var item in targetAttributes)
3443
                {
3444
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
3445
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
3446
                    {
3447
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
3448
                        if (_Attribute != null)
3449
                        {
3450
                            object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
3451
                            if (associItem != null)
3452
                            {
3453
                                if (associItem.GetType() == typeof(Text))
3454
                                {
3455
                                    Text text = associItem as Text;
3456
                                    text.SPPID.RepresentationId = "Attribute";
3457
                                }
3458
                                else if (associItem.GetType() == typeof(Note))
3459
                                {
3460
                                    Note note = associItem as Note;
3461
                                    note.SPPID.RepresentationId = "Attribute";
3462
                                }
3463
                            }
3464
                            _Attribute.set_Value(item.VALUE);
3465
                        }
3466
                            
3467
                    }
3468
                }
3469
                _LMModelItem.Commit();
3470

    
3471
                ReleaseCOMObjects(_Attributes);
3472
                ReleaseCOMObjects(_LMModelItem);
3473
                ReleaseCOMObjects(_LMSymbol);
3474
            }
3475
        }
3476

    
3477
        /// <summary>
3478
        /// Input SpecBreak Attribute
3479
        /// </summary>
3480
        /// <param name="specBreak"></param>
3481
        private void InputSpecBreakAttribute(SpecBreak specBreak)
3482
        {
3483
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3484
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3485

    
3486
            if (upStreamObj != null &&
3487
                downStreamObj != null)
3488
            {
3489
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3490

    
3491
                if (targetLMConnector != null)
3492
                {
3493
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
3494
                    {
3495
                        string symbolPath = _LMLabelPersist.get_FileName();
3496
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
3497
                        if (mapping != null)
3498
                        {
3499
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
3500
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3501
                            {
3502
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
3503
                                if (values.Length == 2)
3504
                                {
3505
                                    string upStreamValue = values[0];
3506
                                    string downStreamValue = values[1];
3507

    
3508
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
3509
                                }
3510
                            }
3511
                        }
3512
                    }
3513

    
3514
                    ReleaseCOMObjects(targetLMConnector);
3515
                }
3516
            }
3517

    
3518

    
3519
            #region 내부에서만 쓰는 메서드
3520
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
3521
            {
3522
                Symbol upStreamSymbol = _upStreamObj as Symbol;
3523
                Line upStreamLine = _upStreamObj as Line;
3524
                Symbol downStreamSymbol = _downStreamObj as Symbol;
3525
                Line downStreamLine = _downStreamObj as Line;
3526
                // 둘다 Line일 경우
3527
                if (upStreamLine != null && downStreamLine != null)
3528
                {
3529
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3530
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3531
                }
3532
                // 둘다 Symbol일 경우
3533
                else if (upStreamSymbol != null && downStreamSymbol != null)
3534
                {
3535
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
3536
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3537
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3538

    
3539
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3540
                    {
3541
                        if (connector.get_ItemStatus() != "Active")
3542
                            continue;
3543

    
3544
                        if (connector.Id != zeroLenthConnector.Id)
3545
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3546
                    }
3547

    
3548
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3549
                    {
3550
                        if (connector.get_ItemStatus() != "Active")
3551
                            continue;
3552

    
3553
                        if (connector.Id != zeroLenthConnector.Id)
3554
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3555
                    }
3556

    
3557
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3558
                    {
3559
                        if (connector.get_ItemStatus() != "Active")
3560
                            continue;
3561

    
3562
                        if (connector.Id != zeroLenthConnector.Id)
3563
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3564
                    }
3565

    
3566
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3567
                    {
3568
                        if (connector.get_ItemStatus() != "Active")
3569
                            continue;
3570

    
3571
                        if (connector.Id != zeroLenthConnector.Id)
3572
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3573
                    }
3574

    
3575
                    ReleaseCOMObjects(zeroLenthConnector);
3576
                    ReleaseCOMObjects(upStreamLMSymbol);
3577
                    ReleaseCOMObjects(downStreamLMSymbol);
3578
                }
3579
                else if (upStreamSymbol != null && downStreamLine != null)
3580
                {
3581
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
3582
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3583
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3584

    
3585
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3586
                    {
3587
                        if (connector.get_ItemStatus() != "Active")
3588
                            continue;
3589

    
3590
                        if (connector.Id == zeroLenthConnector.Id)
3591
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3592
                    }
3593

    
3594
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3595
                    {
3596
                        if (connector.get_ItemStatus() != "Active")
3597
                            continue;
3598

    
3599
                        if (connector.Id == zeroLenthConnector.Id)
3600
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3601
                    }
3602

    
3603
                    ReleaseCOMObjects(zeroLenthConnector);
3604
                    ReleaseCOMObjects(upStreamLMSymbol);
3605
                }
3606
                else if (upStreamLine != null && downStreamSymbol != null)
3607
                {
3608
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
3609
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3610
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3611

    
3612
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3613
                    {
3614
                        if (connector.get_ItemStatus() != "Active")
3615
                            continue;
3616

    
3617
                        if (connector.Id == zeroLenthConnector.Id)
3618
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3619
                    }
3620

    
3621
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3622
                    {
3623
                        if (connector.get_ItemStatus() != "Active")
3624
                            continue;
3625

    
3626
                        if (connector.Id == zeroLenthConnector.Id)
3627
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3628
                    }
3629

    
3630
                    ReleaseCOMObjects(zeroLenthConnector);
3631
                    ReleaseCOMObjects(downStreamLMSymbol);
3632
                }
3633
            }
3634

    
3635
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
3636
            {
3637
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3638
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3639
                {
3640
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3641
                    if (_LMAAttribute != null)
3642
                    {
3643
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3644
                            _LMAAttribute.set_Value(value);
3645
                        else if (_LMAAttribute.get_Value() != value)
3646
                            _LMAAttribute.set_Value(value);
3647
                    }
3648

    
3649
                    _LMModelItem.Commit();
3650
                }
3651
                if (_LMModelItem != null)
3652
                    ReleaseCOMObjects(_LMModelItem);
3653
            }
3654

    
3655
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
3656
            {
3657
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
3658
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3659
                {
3660
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3661
                    if (_LMAAttribute != null)
3662
                    {
3663
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3664
                            _LMAAttribute.set_Value(value);
3665
                        else if (_LMAAttribute.get_Value() != value)
3666
                            _LMAAttribute.set_Value(value);
3667
                    }
3668

    
3669
                    _LMModelItem.Commit();
3670
                }
3671
                if (_LMModelItem != null)
3672
                    ReleaseCOMObjects(_LMModelItem);
3673
            }
3674
            #endregion
3675
        }
3676

    
3677
        /// <summary>
3678
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
3679
        /// </summary>
3680
        /// <param name="text"></param>
3681
        private void TextModeling(Text text)
3682
        {
3683
            LMSymbol _LMSymbol = null;
3684
            LMConnector connectedLMConnector = null;
3685
            //if (text.ASSOCIATION && !string.IsNullOrEmpty(text.OWNER) && text.OWNER != "None")
3686
            if (text.ASSOCIATION)
3687
            {
3688
                object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
3689
                if (owner != null && owner.GetType() == typeof(Symbol))
3690
                {
3691
                    Symbol symbol = owner as Symbol;
3692
                    _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3693
                    if (_LMSymbol != null)
3694
                    {
3695
                        BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3696
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3697
                        {
3698
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3699

    
3700
                            if (mapping != null)
3701
                            {
3702
                                double x = 0;
3703
                                double y = 0;
3704

    
3705
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3706
                                Array array = new double[] { 0, x, y };
3707

    
3708
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3709
                                if (_LMLabelPersist != null)
3710
                                {
3711
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3712
                                    _LMLabelPersist.Commit();
3713
                                    ReleaseCOMObjects(_LMLabelPersist);
3714
                                }
3715
                            }
3716
                        }
3717
                    }
3718
                }
3719
                else if (owner != null && owner.GetType() == typeof(Line))
3720
                {
3721
                    Line line = owner as Line;
3722
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3723
                    connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
3724

    
3725
                    if (connectedLMConnector != null)
3726
                    {
3727
                        BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3728
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3729
                        {
3730
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3731

    
3732
                            if (mapping != null)
3733
                            {
3734
                                double x = 0;
3735
                                double y = 0;
3736

    
3737
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3738
                                Array array = new double[] { 0, x, y };
3739

    
3740
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3741
                                if (_LMLabelPersist != null)
3742
                                {
3743
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3744
                                    _LMLabelPersist.Commit();
3745
                                    ReleaseCOMObjects(_LMLabelPersist);
3746
                                }
3747
                            }
3748
                        }
3749
                    }
3750
                }
3751
            }
3752
            else
3753
            {
3754
                LMItemNote _LMItemNote = null;
3755
                LMAAttribute _LMAAttribute = null;
3756

    
3757
                double x = 0;
3758
                double y = 0;
3759
                double angle = text.ANGLE;
3760
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
3761

    
3762
                _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
3763
                if (_LMSymbol != null)
3764
                {
3765
                    _LMSymbol.Commit();
3766
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3767
                    if (_LMItemNote != null)
3768
                    {
3769
                        _LMItemNote.Commit();
3770
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3771
                        if (_LMAAttribute != null)
3772
                        {
3773
                            _LMAAttribute.set_Value(text.VALUE);
3774
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3775
                            _LMItemNote.Commit();
3776

    
3777
                            if (_LMAAttribute != null)
3778
                                ReleaseCOMObjects(_LMAAttribute);
3779
                            if (_LMItemNote != null)
3780
                                ReleaseCOMObjects(_LMItemNote);
3781
                        }
3782
                    }
3783
                }
3784
            }
3785
            if (_LMSymbol != null)
3786
                ReleaseCOMObjects(_LMSymbol);
3787
        }
3788

    
3789
        /// <summary>
3790
        /// Note Modeling
3791
        /// </summary>
3792
        /// <param name="note"></param>
3793
        private void NoteModeling(Note note)
3794
        {
3795
            LMSymbol _LMSymbol = null;
3796
            LMItemNote _LMItemNote = null;
3797
            LMAAttribute _LMAAttribute = null;
3798

    
3799
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
3800
            {
3801
                double x = 0;
3802
                double y = 0;
3803

    
3804
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
3805

    
3806
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
3807
                if (_LMSymbol != null)
3808
                {
3809
                    _LMSymbol.Commit();
3810
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3811
                    if (_LMItemNote != null)
3812
                    {
3813
                        _LMItemNote.Commit();
3814
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3815
                        if (_LMAAttribute != null)
3816
                        {
3817
                            _LMAAttribute.set_Value(note.VALUE);
3818
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3819
                            _LMItemNote.Commit();
3820
                        }
3821
                    }
3822
                }
3823
            }
3824

    
3825
            if (_LMAAttribute != null)
3826
                ReleaseCOMObjects(_LMAAttribute);
3827
            if (_LMItemNote != null)
3828
                ReleaseCOMObjects(_LMItemNote);
3829
            if (_LMSymbol != null)
3830
                ReleaseCOMObjects(_LMSymbol);
3831
        }
3832

    
3833
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
3834
        {
3835
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
3836
            if (modelItem != null)
3837
            {
3838
                foreach (LMRepresentation rep in modelItem.Representations)
3839
                {
3840
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3841
                    {
3842
                        LMConnector connector = dataSource.GetConnector(rep.Id);
3843
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
3844
                        {
3845
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
3846
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3847
                            if (modelItemIds.Count == 1)
3848
                            {
3849
                                string joinModelItemId = modelItemIds[0];
3850
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3851
                                if (survivorId != null)
3852
                                    break;
3853
                            }
3854
                        }
3855
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
3856
                        {
3857
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
3858
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3859
                            if (modelItemIds.Count == 1)
3860
                            {
3861
                                string joinModelItemId = modelItemIds[0];
3862
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3863
                                if (survivorId != null)
3864
                                    break;
3865
                            }
3866
                        }
3867
                    }
3868
                }
3869
            }
3870
        }
3871

    
3872
        /// <summary>
3873
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
3874
        /// </summary>
3875
        /// <param name="x"></param>
3876
        /// <param name="y"></param>
3877
        /// <param name="originX"></param>
3878
        /// <param name="originY"></param>
3879
        /// <param name="SPPIDLabelLocation"></param>
3880
        /// <param name="location"></param>
3881
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
3882
        {
3883
            if (location == Location.None)
3884
            {
3885
                x = originX;
3886
                y = originY;
3887
            }
3888
            else
3889
            {
3890
                if (location.HasFlag(Location.Center))
3891
                {
3892
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
3893
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
3894
                }
3895

    
3896
                if (location.HasFlag(Location.Left))
3897
                    x = SPPIDLabelLocation.X1;
3898
                else if (location.HasFlag(Location.Right))
3899
                    x = SPPIDLabelLocation.X2;
3900

    
3901
                if (location.HasFlag(Location.Down))
3902
                    y = SPPIDLabelLocation.Y1;
3903
                else if (location.HasFlag(Location.Up))
3904
                    y = SPPIDLabelLocation.Y2;
3905
            }
3906
        }
3907

    
3908
        /// <summary>
3909
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
3910
        /// 1. Angle Valve
3911
        /// 2. 3개로 이루어진 Symbol Group
3912
        /// </summary>
3913
        /// <returns></returns>
3914
        private List<Symbol> GetPrioritySymbol()
3915
        {
3916
            DataTable symbolTable = document.SymbolTable;
3917
            // List에 순서대로 쌓는다.
3918
            List<Symbol> symbols = new List<Symbol>();
3919

    
3920
            // Angle Valve 부터
3921
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
3922
            {
3923
                if (!symbols.Contains(symbol))
3924
                {
3925
                    double originX = 0;
3926
                    double originY = 0;
3927

    
3928
                    // ID2 Table에서 Original Point 가져옴.
3929
                    string OriginalPoint = symbolTable.Select(string.Format("UID = {0}", symbol.DBUID))[0]["OriginalPoint"].ToString();
3930
                    SPPIDUtil.ConvertPointBystring(OriginalPoint, ref originX, ref originY);
3931

    
3932
                    SlopeType slopeType1 = SlopeType.None;
3933
                    SlopeType slopeType2 = SlopeType.None;
3934
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
3935
                    {
3936
                        double connectorX = 0;
3937
                        double connectorY = 0;
3938
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
3939
                        if (slopeType1 == SlopeType.None)
3940
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3941
                        else
3942
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3943
                    }
3944

    
3945
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
3946
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
3947
                        symbols.Add(symbol);
3948
                }
3949
            }
3950

    
3951
            List<Symbol> tempSymbols = new List<Symbol>();
3952
            // Conn 갯수 기준
3953
            foreach (var item in document.SYMBOLS)
3954
            {
3955
                if (!symbols.Contains(item))
3956
                    tempSymbols.Add(item);
3957
            }
3958
            tempSymbols.Sort(SortSymbolPriority);
3959
            symbols.AddRange(tempSymbols);
3960

    
3961
            return symbols;
3962
        }
3963

    
3964
        private void SetPriorityLine(List<Line> lines)
3965
        {
3966
            lines.Sort(SortLinePriority);
3967

    
3968
            int SortLinePriority(Line a, Line b)
3969
            {
3970
                // Branch 없는것부터
3971
                int branchRetval = CompareBranchLine(a, b);
3972
                if (branchRetval != 0)
3973
                {
3974
                    return branchRetval;
3975
                }
3976
                else
3977
                {
3978
                    // Symbol 연결 갯수
3979
                    int connSymbolRetval = CompareConnSymbol(a, b);
3980
                    if (connSymbolRetval != 0)
3981
                    {
3982
                        return connSymbolRetval;
3983
                    }
3984
                    else
3985
                    {
3986
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
3987
                        int connItemRetval = CompareConnItem(a, b);
3988
                        if (connItemRetval != 0)
3989
                        {
3990
                            return connItemRetval;
3991
                        }
3992
                        else
3993
                        {
3994
                            // ConnectedItem이 없는것
3995
                            int noneConnRetval = CompareNoneConn(a, b);
3996
                            if (noneConnRetval != 0)
3997
                            {
3998
                                return noneConnRetval;
3999
                            }
4000
                            else
4001
                            {
4002

    
4003
                            }
4004
                        }
4005
                    }
4006
                }
4007

    
4008
                return 0;
4009
            }
4010

    
4011
            int CompareNotSegmentLine(Line a, Line b)
4012
            {
4013
                List<Connector> connectorsA = a.CONNECTORS
4014
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4015
                    .ToList();
4016

    
4017
                List<Connector> connectorsB = b.CONNECTORS
4018
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4019
                    .ToList();
4020

    
4021
                // 오름차순
4022
                return connectorsB.Count.CompareTo(connectorsA.Count);
4023
            }
4024

    
4025
            int CompareConnSymbol(Line a, Line b)
4026
            {
4027
                List<Connector> connectorsA = a.CONNECTORS
4028
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4029
                    .ToList();
4030

    
4031
                List<Connector> connectorsB = b.CONNECTORS
4032
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4033
                    .ToList();
4034

    
4035
                // 오름차순
4036
                return connectorsB.Count.CompareTo(connectorsA.Count);
4037
            }
4038

    
4039
            int CompareConnItem(Line a, Line b)
4040
            {
4041
                List<Connector> connectorsA = a.CONNECTORS
4042
                    .Where(conn => conn.ConnectedObject != null && 
4043
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
4044
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
4045
                    .ToList();
4046

    
4047
                List<Connector> connectorsB = b.CONNECTORS
4048
                    .Where(conn => conn.ConnectedObject != null &&
4049
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
4050
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
4051
                    .ToList();
4052

    
4053
                // 오름차순
4054
                return connectorsB.Count.CompareTo(connectorsA.Count);
4055
            }
4056

    
4057
            int CompareBranchLine(Line a, Line b)
4058
            {
4059
                List<Connector> connectorsA = a.CONNECTORS
4060
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
4061
                    .ToList();
4062
                List<Connector> connectorsB = b.CONNECTORS
4063
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
4064
                    .ToList();
4065

    
4066
                // 내림차순
4067
                return connectorsA.Count.CompareTo(connectorsB.Count);
4068
            }
4069

    
4070
            int CompareNoneConn(Line a, Line b)
4071
            {
4072
                List<Connector> connectorsA = a.CONNECTORS
4073
                    .Where(conn => conn.ConnectedObject == null)
4074
                    .ToList();
4075

    
4076
                List<Connector> connectorsB = b.CONNECTORS
4077
                    .Where(conn => conn.ConnectedObject == null)
4078
                    .ToList();
4079

    
4080
                // 오름차순
4081
                return connectorsB.Count.CompareTo(connectorsA.Count);
4082
            }
4083
        }
4084

    
4085
        private void SortBranchLines()
4086
        {
4087
            BranchLines.Sort(SortBranchLine);
4088
            int SortBranchLine(Line a, Line b)
4089
            {
4090
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4091
                 x.ConnectedObject.GetType() == typeof(Line) &&
4092
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
4093
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4094

    
4095
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4096
                 x.ConnectedObject.GetType() == typeof(Line) &&
4097
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
4098
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4099

    
4100
                // 내림차순
4101
                return countA.CompareTo(countB);
4102
            }
4103
        }
4104

    
4105
        private static int SortSymbolPriority(Symbol a, Symbol b)
4106
        {
4107
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4108
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4109
            int retval = countB.CompareTo(countA);
4110
            if (retval != 0)
4111
                return retval;
4112
            else
4113
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
4114
        }
4115

    
4116
        private string GetSPPIDFileName(LMModelItem modelItem)
4117
        {
4118
            string symbolPath = null;
4119
            foreach (LMRepresentation rep in modelItem.Representations)
4120
            {
4121
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4122
                {
4123
                    symbolPath = rep.get_FileName();
4124
                    break;
4125
                }
4126
            }
4127
            return symbolPath;
4128
        }
4129

    
4130
        private string GetSPPIDFileName(string modelItemId)
4131
        {
4132
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4133
            string symbolPath = null;
4134
            foreach (LMRepresentation rep in modelItem.Representations)
4135
            {
4136
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4137
                {
4138
                    symbolPath = rep.get_FileName();
4139
                    break;
4140
                }
4141
            }
4142
            ReleaseCOMObjects(modelItem);
4143
            return symbolPath;
4144
        }
4145

    
4146
        /// <summary>
4147
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
4148
        /// </summary>
4149
        /// <param name="graphicOID"></param>
4150
        /// <param name="milliseconds"></param>
4151
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
4152
        {
4153
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
4154
            {
4155
                double minX = 0;
4156
                double minY = 0;
4157
                double maxX = 0;
4158
                double maxY = 0;
4159
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
4160
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
4161

    
4162
                Thread.Sleep(milliseconds);
4163
            }
4164
        }
4165

    
4166
        /// <summary>
4167
        /// ComObject를 Release
4168
        /// </summary>
4169
        /// <param name="objVars"></param>
4170
        public void ReleaseCOMObjects(params object[] objVars)
4171
        {
4172
            if (objVars != null)
4173
            {
4174
                int intNewRefCount = 0;
4175
                foreach (object obj in objVars)
4176
                {
4177
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
4178
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
4179
                }
4180
            }
4181
        }
4182

    
4183
        /// IDisposable 구현
4184
        ~AutoModeling()
4185
        {
4186
            this.Dispose(false);
4187
        }
4188

    
4189
        private bool disposed;
4190
        public void Dispose()
4191
        {
4192
            this.Dispose(true);
4193
            GC.SuppressFinalize(this);
4194
        }
4195

    
4196
        protected virtual void Dispose(bool disposing)
4197
        {
4198
            if (this.disposed) return;
4199
            if (disposing)
4200
            {
4201
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
4202
            }
4203
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
4204
            this.disposed = true;
4205
        }
4206
    }
4207
}
클립보드 이미지 추가 (최대 크기: 500 MB)