프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ c9a4db3a

이력 | 보기 | 이력해설 | 다운로드 (261 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, 23);
92
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
93

    
94
                    // VendorPackage Modeling
95
                    RunVendorPackageModeling();
96
                    // Equipment Modeling
97
                    RunEquipmentModeling();
98
                    // Symbol Modeling
99
                    RunSymbolModeling();
100
                    // LineRun Line Modeling
101
                    RunLineModeling();
102
                    // Vent Drain Modeling
103
                    RunVentDrainModeling();
104
                    // Clear Attribute
105
                    RunClearNominalDiameter();
106
                    // Join SameConnector
107
                    RunJoinRunForSameConnector();
108
                    // Join Run
109
                    RunJoinRun();
110
                    // EndBreak Modeling
111
                    RunEndBreakModeling();
112
                    // SpecBreak Modeling
113
                    RunSpecBreakModeling();
114
                    //Line Number Modeling
115
                    RunLineNumberModeling();
116
                    // Note Modeling
117
                    RunNoteModeling();
118
                    // Text Modeling
119
                    RunTextModeling();
120
                    // Input LineNumber Attribute
121
                    RunInputLineNumberAttribute();
122
                    // Input Symbol Attribute
123
                    RunInputSymbolAttribute();
124
                    // Input SpecBreak Attribute
125
                    RunInputSpecBreakAttribute();
126
                    // Input EndBreak Attribute
127
                    RunInputEndBreakAttribute();
128
                    // Label Symbol Modeling
129
                    RunLabelSymbolModeling();
130
                    // Correct Text
131
                    RunCorrectAssociationText();
132

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

    
158
                Log.Write("End Modeling");
159
                radApp.ActiveWindow.Fit();
160

    
161
                ReleaseCOMObjects(application);
162
                application = null;
163
                if (radApp.ActiveDocument != null)
164
                {
165
                    if (closeDocument && newDrawing != null)
166
                    {
167
                        newDrawing.Save();
168
                        newDrawing.CloseDrawing(true);
169
                        ReleaseCOMObjects(newDrawing);
170
                        newDrawing = null;
171
                    }
172
                    else if (newDrawing == null)
173
                    {
174
                        Log.Write("error document");
175
                    }
176
                }
177

    
178
                ReleaseCOMObjects(dataSource);
179
                dataSource = null;
180
                ReleaseCOMObjects(_placement);
181
                _placement = null;
182

    
183
                Thread.Sleep(1000);
184
            }
185
        }
186

    
187
        private void RunVendorPackageModeling()
188
        {
189
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VendorPackages.Count);
190
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "VendorPackages Modeling");
191
            foreach (VendorPackage item in document.VendorPackages)
192
            {
193
                try
194
                {
195
                    VendorPackageModeling(item);
196
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
197
                }
198
                catch (Exception ex)
199
                {
200
                    Log.Write("Error in RunVendorPackageModeling");
201
                    Log.Write("UID : " + item.UID);
202
                    Log.Write(ex.Message);
203
                    Log.Write(ex.StackTrace);
204
                }
205
            }
206
        }
207
        private void RunEquipmentModeling()
208
        {
209
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
210
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
211
            foreach (Equipment item in document.Equipments)
212
            {
213
                try
214
                {
215
                    EquipmentModeling(item);
216
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
217
                }
218
                catch (Exception ex)
219
                {
220
                    Log.Write("Error in EquipmentModeling");
221
                    Log.Write("UID : " + item.UID);
222
                    Log.Write(ex.Message);
223
                    Log.Write(ex.StackTrace);
224
                }
225
            }
226
        }
227
        private void RunSymbolModeling()
228
        {
229
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
230
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
231
            prioritySymbols = GetPrioritySymbol();
232
            foreach (var item in prioritySymbols)
233
            {
234
                try
235
                {
236
                    if (document.VentDrainSymbol.Contains(item))
237
                        continue;
238
                    SymbolModelingBySymbol(item);
239
                }
240
                catch (Exception ex)
241
                {
242
                    Log.Write("Error in SymbolModelingByPriority");
243
                    Log.Write("UID : " + item.UID);
244
                    Log.Write(ex.Message);
245
                    Log.Write(ex.StackTrace);
246
                }
247
            }
248
        }
249
        private void RunLineModeling()
250
        {
251
            List<Line> AllLine = document.LINES.ToList();
252
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
253
            !SPPIDUtil.IsBranchedLine(document, x));
254
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
255

    
256
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
257
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
258

    
259
            SetPriorityLine(step1_Line);
260
            foreach (var item in step1_Line)
261
            {
262
                try
263
                {
264
                    if (document.VentDrainLine.Contains(item))
265
                        continue;
266
                    NewLineModeling(item);
267
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
268
                }
269
                catch (Exception ex)
270
                {
271
                    Log.Write("Error in NewLineModeling");
272
                    Log.Write("UID : " + item.UID);
273
                    Log.Write(ex.Message);
274
                    Log.Write(ex.StackTrace);
275
                }
276
            }
277

    
278
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
279
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 2");
280
            int branchCount = BranchLines.Count;
281
            while (BranchLines.Count > 0)
282
            {
283
                try
284
                {
285
                    SortBranchLines();
286
                    Line item = BranchLines[0];
287
                    NewLineModeling(item, true);
288
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
289
                }
290
                catch (Exception ex)
291
                {
292
                    Log.Write("Error in NewLineModeling");
293
                    Log.Write("UID : " + BranchLines[0].UID);
294
                    Log.Write(ex.Message);
295
                    Log.Write(ex.StackTrace);
296
                    BranchLines.Remove(BranchLines[0]);
297
                }
298
            }
299

    
300
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
301
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
302
            foreach (var item in stepLast_Line)
303
            {
304
                try
305
                {
306
                    if (document.VentDrainLine.Contains(item))
307
                        continue;
308
                    NewLineModeling(item);
309
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
310
                }
311
                catch (Exception ex)
312
                {
313
                    Log.Write("Error in NewLineModeling");
314
                    Log.Write("UID : " + item.UID);
315
                    Log.Write(ex.Message);
316
                    Log.Write(ex.StackTrace);
317
                }
318
            }
319
        }
320
        private void RunVentDrainModeling()
321
        {
322
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VentDrainLine.Count);
323
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Vent Drain Modeling");
324
            foreach (var item in document.VentDrainLine)
325
            {
326
                try
327
                {
328
                    Connector connector = item.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
329
                    if (connector != null)
330
                    {
331
                        SetCoordinate();
332
                        SymbolModelingBySymbol(connector.ConnectedObject as Symbol);
333
                        NewLineModeling(item, true);
334
                    }
335
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
336
                }
337
                catch (Exception ex)
338
                {
339
                    Log.Write("Error in NewLineModeling");
340
                    Log.Write("UID : " + item.UID);
341
                    Log.Write(ex.Message);
342
                    Log.Write(ex.StackTrace);
343
                }
344

    
345
                void SetCoordinate()
346
                {
347
                    Connector branchConnector = item.CONNECTORS.Find(loop => loop.ConnectedObject != null && loop.ConnectedObject.GetType() == typeof(Line));
348
                    if (branchConnector != null)
349
                    {
350
                        Line connLine = branchConnector.ConnectedObject as Line;
351
                        double x = 0;
352
                        double y = 0;
353
                        GetTargetLineConnectorPoint(branchConnector, item, ref x, ref y);
354
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(item, connLine, ref x, ref y);
355
                        if (targetConnector != null)
356
                        {
357
                            List<Symbol> group = new List<Symbol>();
358
                            SPPIDUtil.FindConnectedSymbolGroup(document, item.CONNECTORS.Find(loop => loop != branchConnector).ConnectedObject as Symbol, group);
359
                            if (item.SlopeType == SlopeType.HORIZONTAL)
360
                            {
361
                                item.SPPID.START_Y = y;
362
                                item.SPPID.END_Y = y;
363
                                foreach (var symbol in group)
364
                                {
365
                                    symbol.SPPID.ORIGINAL_Y = y;
366
                                    symbol.SPPID.SPPID_Y = y;
367
                                }
368
                            }
369
                            else if (item.SlopeType == SlopeType.VERTICAL)
370
                            {
371
                                item.SPPID.START_X = x;
372
                                item.SPPID.END_X = x;
373
                                foreach (var symbol in group)
374
                                {
375
                                    symbol.SPPID.ORIGINAL_X = x;
376
                                    symbol.SPPID.SPPID_X = x;
377
                                }
378
                            }
379
                        }
380
                        ReleaseCOMObjects(targetConnector);
381
                        targetConnector = null;
382
                    }
383
                }
384
            }
385
        }
386
        private void RunClearNominalDiameter()
387
        {
388
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
389
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
390
            List<string> endClearModelItemID = new List<string>();
391
            for (int i = 0; i < document.LINES.Count; i++)
392
            {
393
                Line item = document.LINES[i];
394
                string modelItemID = item.SPPID.ModelItemId;
395
                if (!string.IsNullOrEmpty(modelItemID))
396
                {
397
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
398
                    if (modelItem != null)
399
                    {
400
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
401
                        if (attribute != null)
402
                            attribute.set_Value(DBNull.Value);
403

    
404
                        modelItem.Commit();
405
                        ReleaseCOMObjects(modelItem);
406
                        modelItem = null;
407
                    }
408
                }
409
                if (!endClearModelItemID.Contains(modelItemID))
410
                    endClearModelItemID.Add(modelItemID);
411
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
412
            }
413
            for (int i = 0; i < document.SYMBOLS.Count; i++)
414
            {
415
                Symbol item = document.SYMBOLS[i];
416
                string repID = item.SPPID.RepresentationId;
417
                string modelItemID = item.SPPID.ModelItemID;
418
                if (!string.IsNullOrEmpty(modelItemID))
419
                {
420
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
421
                    if (modelItem != null)
422
                    {
423
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
424
                        if (attribute != null)
425
                            attribute.set_Value(DBNull.Value);
426
                        int index = 1;
427
                        while (true)
428
                        {
429
                            attribute = modelItem.Attributes[string.Format("PipingPoint{0}.NominalDiameter", index)];
430
                            if (attribute != null)
431
                                attribute.set_Value(DBNull.Value);
432
                            else
433
                                break;
434
                            index++;
435
                        }
436
                        modelItem.Commit();
437
                        ReleaseCOMObjects(modelItem);
438
                        modelItem = null;
439
                    }
440
                }
441
                if (!string.IsNullOrEmpty(repID))
442
                {
443
                    LMSymbol symbol = dataSource.GetSymbol(repID);
444
                    if (symbol != null)
445
                    {
446
                        foreach (LMConnector connector in symbol.Connect1Connectors)
447
                        {
448
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
449
                            {
450
                                endClearModelItemID.Add(connector.ModelItemID);
451
                                LMModelItem modelItem = connector.ModelItemObject;
452
                                if (modelItem != null)
453
                                {
454
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
455
                                    if (attribute != null)
456
                                        attribute.set_Value(DBNull.Value);
457

    
458
                                    modelItem.Commit();
459
                                    ReleaseCOMObjects(modelItem);
460
                                    modelItem = null;
461
                                }
462
                            }
463
                        }
464
                        foreach (LMConnector connector in symbol.Connect2Connectors)
465
                        {
466
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
467
                            {
468
                                endClearModelItemID.Add(connector.ModelItemID);
469
                                LMModelItem modelItem = connector.ModelItemObject;
470
                                if (modelItem != null)
471
                                {
472
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
473
                                    if (attribute != null)
474
                                        attribute.set_Value(DBNull.Value);
475

    
476
                                    modelItem.Commit();
477
                                    ReleaseCOMObjects(modelItem);
478
                                    modelItem = null;
479
                                }
480
                            }
481
                        }
482
                    }
483
                    ReleaseCOMObjects(symbol);
484
                    symbol = null;
485
                }
486
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
487
            }
488
        }
489
        private void RunClearValueInconsistancy()
490
        {
491
            int count = 1;
492
            bool loop = true;
493
            while (loop)
494
            {
495
                loop = false;
496
                LMAFilter filter = new LMAFilter();
497
                LMACriterion criterion = new LMACriterion();
498
                filter.ItemType = "Relationship";
499
                criterion.SourceAttributeName = "SP_DRAWINGID";
500
                criterion.Operator = "=";
501
                criterion.set_ValueAttribute(drawingID);
502
                filter.get_Criteria().Add(criterion);
503

    
504
                LMRelationships relationships = new LMRelationships();
505
                relationships.Collect(dataSource, Filter: filter);
506

    
507
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
508
                if (count > 1)
509
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
510
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
511
                foreach (LMRelationship relationship in relationships)
512
                {
513
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
514
                    {
515
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
516
                        {
517
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
518
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
519
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
520
                            if (modelItem1 != null)
521
                            {
522
                                string attrName = array[0];
523
                                if (attrName.Contains("PipingPoint"))
524
                                {
525
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
526
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
527
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
528
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
529
                                    {
530
                                        loop = true;
531
                                        attribute1.set_Value(DBNull.Value);
532
                                    }
533
                                    attribute1 = null;
534
                                }
535
                                else
536
                                {
537
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
538
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
539
                                    {
540
                                        loop = true;
541
                                        attribute1.set_Value(DBNull.Value);
542
                                    }
543
                                    attribute1 = null;
544
                                }
545
                                modelItem1.Commit();
546
                            }
547
                            if (modelItem2 != null)
548
                            {
549
                                string attrName = array[1];
550
                                if (attrName.Contains("PipingPoint"))
551
                                {
552
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
553
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
554
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
555
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
556
                                    {
557
                                        attribute2.set_Value(DBNull.Value);
558
                                        loop = true;
559
                                    }
560
                                    attribute2 = null;
561
                                }
562
                                else
563
                                {
564
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
565
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
566
                                    {
567
                                        attribute2.set_Value(DBNull.Value);
568
                                        loop = true;
569
                                    }
570
                                    attribute2 = null;
571
                                }
572
                                modelItem2.Commit();
573
                            }
574
                            ReleaseCOMObjects(modelItem1);
575
                            modelItem1 = null;
576
                            ReleaseCOMObjects(modelItem2);
577
                            modelItem2 = null;
578
                            inconsistency.Commit();
579
                        }
580
                        ReleaseCOMObjects(inconsistency);
581
                    }
582
                    relationship.Commit();
583
                    ReleaseCOMObjects(relationship);
584
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
585
                }
586
                ReleaseCOMObjects(filter);
587
                filter = null;
588
                ReleaseCOMObjects(criterion);
589
                criterion = null;
590
                ReleaseCOMObjects(relationships);
591
                relationships = null;
592
                count++;
593
            }
594
        }
595
        private void RunEndBreakModeling()
596
        {
597
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
598
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
599
            foreach (var item in document.EndBreaks)
600
                try
601
                {
602
                    EndBreakModeling(item);
603
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
604
                }
605
                catch (Exception ex)
606
                {
607
                    Log.Write("Error in EndBreakModeling");
608
                    Log.Write("UID : " + item.UID);
609
                    Log.Write(ex.Message);
610
                    Log.Write(ex.StackTrace);
611
                }
612
        }
613
        private void RunSpecBreakModeling()
614
        {
615
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
616
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
617
            foreach (var item in document.SpecBreaks)
618
                try
619
                {
620
                    SpecBreakModeling(item);
621
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
622
                }
623
                catch (Exception ex)
624
                {
625
                    Log.Write("Error in SpecBreakModeling");
626
                    Log.Write("UID : " + item.UID);
627
                    Log.Write(ex.Message);
628
                    Log.Write(ex.StackTrace);
629
                }
630
        }
631
        private void RunJoinRunForSameConnector()
632
        {
633
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
634
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
635
            foreach (var line in document.LINES)
636
            {
637
                Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(line.SPPID.ModelItemId, false);
638
                List<List<double[]>> result = new List<List<double[]>>();
639
                foreach (var item in vertices)
640
                {
641
                    ReleaseCOMObjects(item.Key);
642
                    result.Add(item.Value);
643
                }
644
                line.SPPID.Vertices = result;
645
                vertices = null;
646
            }
647

    
648
            foreach (var line in document.LINES)
649
            {
650
                foreach (var connector in line.CONNECTORS)
651
                {
652
                    if (connector.ConnectedObject != null &&
653
                        connector.ConnectedObject.GetType() == typeof(Line) &&
654
                        !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
655
                    {
656
                        Line connLine = connector.ConnectedObject as Line;
657
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
658
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
659
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
660
                            !SPPIDUtil.IsSegment(document, line, connLine))
661
                        {
662
                            string survivorId = string.Empty;
663
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
664
                        }
665

    
666
                    }
667
                }
668
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
669
            }
670

    
671
            foreach (var line in document.LINES)
672
                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
673
        }
674
        private void RunJoinRun()
675
        {
676
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
677
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
678
            List<string> endModelID = new List<string>();
679
            foreach (var line in document.LINES)
680
            {
681
                if (!endModelID.Contains(line.SPPID.ModelItemId))
682
                {
683
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
684
                    {
685
                        string survivorId = string.Empty;
686
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
687
                        if (string.IsNullOrEmpty(survivorId))
688
                        {
689
                            endModelID.Add(line.SPPID.ModelItemId);
690
                        }
691
                    }
692
                }
693
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
694
            }
695
        }
696
        private void RunLineNumberModeling()
697
        {
698
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
699
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
700
            foreach (var item in document.LINENUMBERS)
701
            {
702
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
703
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
704
                {
705
                    ReleaseCOMObjects(label);
706
                    item.SPPID.RepresentationId = null;
707
                    LineNumberModeling(item);
708
                }
709
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
710
            }
711
        }
712
        private void RunNoteModeling()
713
        {
714
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
715
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
716
            List<Note> correctList = new List<Note>();
717
            foreach (var item in document.NOTES)
718
                try
719
                {
720
                    NoteModeling(item, correctList);
721
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
722
                }
723
                catch (Exception ex)
724
                {
725
                    Log.Write("Error in NoteModeling");
726
                    Log.Write("UID : " + item.UID);
727
                    Log.Write(ex.Message);
728
                    Log.Write(ex.StackTrace);
729
                }
730

    
731
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
732
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
733
            SortNote(correctList);
734
            List<Note> endList = new List<Note>();
735
            if (correctList.Count > 0)
736
                endList.Add(correctList[0]);
737
            foreach (var item in correctList)
738
                try
739
                {
740
                    if (!endList.Contains(item))
741
                        NoteCorrectModeling(item, endList);
742
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
743
                }
744
                catch (Exception ex)
745
                {
746
                    Log.Write("Error in NoteModeling");
747
                    Log.Write("UID : " + item.UID);
748
                    Log.Write(ex.Message);
749
                    Log.Write(ex.StackTrace);
750
                }
751
        }
752
        private void RunTextModeling()
753
        {
754
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
755
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
756
            SortText(document.TEXTINFOS);
757
            foreach (var item in document.TEXTINFOS)
758
                try
759
                {
760
                    if (item.ASSOCIATION)
761
                        AssociationTextModeling(item);
762
                    else
763
                        NormalTextModeling(item);
764
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
765
                }
766
                catch (Exception ex)
767
                {
768
                    Log.Write("Error in TextModeling");
769
                    Log.Write("UID : " + item.UID);
770
                    Log.Write(ex.Message);
771
                    Log.Write(ex.StackTrace);
772
                }
773
        }
774
        private void RunInputLineNumberAttribute()
775
        {
776
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
777
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
778
            List<string> endLine = new List<string>();
779
            foreach (var item in document.LINENUMBERS)
780
                try
781
                {
782
                    InputLineNumberAttribute(item, endLine);
783
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
784
                }
785
                catch (Exception ex)
786
                {
787
                    Log.Write("Error in InputLineNumberAttribute");
788
                    Log.Write("UID : " + item.UID);
789
                    Log.Write(ex.Message);
790
                    Log.Write(ex.StackTrace);
791
                }
792
        }
793
        private void RunInputSymbolAttribute()
794
        {
795
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
796
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
797
            foreach (var item in document.SYMBOLS)
798
                try
799
                {
800
                    InputSymbolAttribute(item, item.ATTRIBUTES);
801
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
802
                }
803
                catch (Exception ex)
804
                {
805
                    Log.Write("Error in InputSymbolAttribute");
806
                    Log.Write("UID : " + item.UID);
807
                    Log.Write(ex.Message);
808
                    Log.Write(ex.StackTrace);
809
                }
810
        }
811
        private void RunInputSpecBreakAttribute()
812
        {
813
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
814
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
815
            foreach (var item in document.SpecBreaks)
816
                try
817
                {
818
                    InputSpecBreakAttribute(item);
819
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
820
                }
821
                catch (Exception ex)
822
                {
823
                    Log.Write("Error in InputSpecBreakAttribute");
824
                    Log.Write("UID : " + item.UID);
825
                    Log.Write(ex.Message);
826
                    Log.Write(ex.StackTrace);
827
                }
828
        }
829
        private void RunInputEndBreakAttribute()
830
        {
831
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
832
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
833
            foreach (var item in document.EndBreaks)
834
                try
835
                {
836
                    InputEndBreakAttribute(item);
837
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
838
                }
839
                catch (Exception ex)
840
                {
841
                    Log.Write("Error in RunInputEndBreakAttribute");
842
                    Log.Write("UID : " + item.UID);
843
                    Log.Write(ex.Message);
844
                    Log.Write(ex.StackTrace);
845
                }
846
        }
847
        private void RunLabelSymbolModeling()
848
        {
849
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
850
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
851
            foreach (var item in document.SYMBOLS)
852
                try
853
                {
854
                    LabelSymbolModeling(item);
855
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
856
                }
857
                catch (Exception ex)
858
                {
859
                    Log.Write("Error in LabelSymbolModeling");
860
                    Log.Write("UID : " + item.UID);
861
                    Log.Write(ex.Message);
862
                    Log.Write(ex.StackTrace);
863
                }
864
        }
865
        private void RunCorrectAssociationText()
866
        {
867
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
868
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
869
            List<Text> endTexts = new List<Text>();
870
            foreach (var item in document.TEXTINFOS)
871
            {
872
                try
873
                {
874
                    if (item.ASSOCIATION && !endTexts.Contains(item))
875
                        AssociationTextCorrectModeling(item, endTexts);
876
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
877
                }
878
                catch (Exception ex)
879
                {
880
                    Log.Write("Error in RunCorrectAssociationText");
881
                    Log.Write("UID : " + item.UID);
882
                    Log.Write(ex.Message);
883
                    Log.Write(ex.StackTrace);
884
                }
885
                
886
            }
887

    
888
            foreach (var item in document.LINENUMBERS)
889
            {
890
                try
891
                {
892
                    LineNumberCorrectModeling(item);
893
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
894
                }
895
                catch (Exception ex)
896
                {
897
                    Log.Write("Error in RunCorrectAssociationText");
898
                    Log.Write("UID : " + item.UID);
899
                    Log.Write(ex.Message);
900
                    Log.Write(ex.StackTrace);
901
                }
902
            }
903
        }
904
        /// <summary>
905
        /// 도면 생성 메서드
906
        /// </summary>
907
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
908
        {
909
            Log.Write("------------------ Start create document ------------------");
910
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
911
            Log.Write("Drawing name : " + drawingName);
912
            Log.Write("Drawing number : " + drawingNumber);
913
            Thread.Sleep(1000);
914
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
915
            if (newDrawing != null)
916
            {
917
                document.SPPID_DrawingNumber = drawingNumber;
918
                document.SPPID_DrawingName = drawingName;
919
                Thread.Sleep(1000);
920
                radApp.ActiveWindow.Fit();
921
                Thread.Sleep(1000);
922
                radApp.ActiveWindow.Zoom = 2000;
923
                Thread.Sleep(2000);
924

    
925
                //current LMDrawing 가져오기
926
                LMAFilter filter = new LMAFilter();
927
                LMACriterion criterion = new LMACriterion();
928
                filter.ItemType = "Drawing";
929
                criterion.SourceAttributeName = "Name";
930
                criterion.Operator = "=";
931
                criterion.set_ValueAttribute(drawingName);
932
                filter.get_Criteria().Add(criterion);
933

    
934
                LMDrawings drawings = new LMDrawings();
935
                drawings.Collect(dataSource, Filter: filter);
936

    
937
                drawingID = ((dynamic)drawings).Nth(1).Id;
938
                ReleaseCOMObjects(filter);
939
                ReleaseCOMObjects(criterion);
940
                ReleaseCOMObjects(drawings);
941
                filter = null;
942
                criterion = null;
943
                drawings = null;
944
            }
945
            else
946
                Log.Write("Fail Create Drawing");
947

    
948
            if (newDrawing != null)
949
                return true;
950
            else
951
                return false;
952
        }
953

    
954
        /// <summary>
955
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
956
        /// </summary>
957
        /// <param name="drawingName"></param>
958
        /// <param name="drawingNumber"></param>
959
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
960
        {
961
            LMDrawings drawings = new LMDrawings();
962
            drawings.Collect(dataSource);
963

    
964
            List<string> drawingNameList = new List<string>();
965
            List<string> drawingNumberList = new List<string>();
966

    
967
            foreach (LMDrawing item in drawings)
968
            {
969
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
970
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
971
            }
972

    
973
            int nameLength = drawingName.Length;
974
            while (drawingNameList.Contains(drawingName))
975
            {
976
                if (nameLength == drawingName.Length)
977
                    drawingName += "-1";
978
                else
979
                {
980
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
981
                    drawingName = drawingName.Substring(0, nameLength + 1);
982
                    drawingName += ++index;
983
                }
984
            }
985

    
986
            int numberLength = drawingNumber.Length;
987
            while (drawingNameList.Contains(drawingNumber))
988
            {
989
                if (numberLength == drawingNumber.Length)
990
                    drawingNumber += "-1";
991
                else
992
                {
993
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
994
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
995
                    drawingNumber += ++index;
996
                }
997
            }
998
            ReleaseCOMObjects(drawings);
999
            drawings = null;
1000
        }
1001

    
1002
        /// <summary>
1003
        /// 도면 크기 구하는 메서드
1004
        /// </summary>
1005
        /// <returns></returns>
1006
        private bool DocumentCoordinateCorrection()
1007
        {
1008
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1009
            {
1010
                Log.Write("Setting Drawing X, Drawing Y");
1011
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1012
                Log.Write("Start coordinate correction");
1013
                document.CoordinateCorrection();
1014
                return true;
1015
            }
1016
            else
1017
            {
1018
                Log.Write("Need Drawing X, Y");
1019
                return false;
1020
            }
1021
        }
1022

    
1023
        /// <summary>
1024
        /// 심볼을 실제로 Modeling 메서드
1025
        /// </summary>
1026
        /// <param name="symbol">생성할 심볼</param>
1027
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1028
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1029
        {
1030
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1031
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1032
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1033
                return;
1034
            // 이미 모델링 됐을 경우
1035
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1036
                return;
1037

    
1038
            LMSymbol _LMSymbol = null;
1039

    
1040
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1041
            double x = symbol.SPPID.ORIGINAL_X;
1042
            double y = symbol.SPPID.ORIGINAL_Y;
1043
            int mirror = 0;
1044
            double angle = symbol.ANGLE;
1045

    
1046
            // OPC 일경우 180도 일때 Mirror
1047
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1048
                mirror = 1;
1049

    
1050
            // Mirror 계산
1051
            if (symbol.FLIP == 1)
1052
            {
1053
                mirror = 1;
1054
                angle += Math.PI;
1055
            }
1056

    
1057
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1058
            {
1059
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1060
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1061
                if (connector != null)
1062
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1063

    
1064
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1065
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1066
                if (temp != null)
1067
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1068
                ReleaseCOMObjects(temp);
1069
                temp = null;
1070

    
1071
                if (_LMSymbol != null && _TargetItem != null)
1072
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1073

    
1074
                ReleaseCOMObjects(_TargetItem);
1075
            }
1076
            else
1077
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1078

    
1079
            if (_LMSymbol != null)
1080
            {
1081
                _LMSymbol.Commit();
1082

    
1083
                // ConnCheck
1084
                List<string> ids = new List<string>();
1085
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1086
                {
1087
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1088
                        ids.Add(item.Id);
1089
                    ReleaseCOMObjects(item);
1090
                }
1091
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1092
                {
1093
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1094
                        ids.Add(item.Id);
1095
                    ReleaseCOMObjects(item);
1096
                }
1097

    
1098
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1099
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1100
                {
1101
                    double currentX = _LMSymbol.get_XCoordinate();
1102
                    double currentY = _LMSymbol.get_YCoordinate();
1103

    
1104

    
1105
                }
1106

    
1107
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1108
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1109
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1110

    
1111
                foreach (var item in symbol.ChildSymbols)
1112
                    CreateChildSymbol(item, _LMSymbol, symbol);
1113

    
1114
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1115
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1116

    
1117
                double[] range = null;
1118
                GetSPPIDSymbolRange(symbol, ref range);
1119
                symbol.SPPID.SPPID_Min_X = range[0];
1120
                symbol.SPPID.SPPID_Min_Y = range[1];
1121
                symbol.SPPID.SPPID_Max_X = range[2];
1122
                symbol.SPPID.SPPID_Max_Y = range[3];
1123

    
1124
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1125
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1126
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1127
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1128

    
1129
                ReleaseCOMObjects(_LMSymbol);
1130
            }
1131
        }
1132
        /// <summary>
1133
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1134
        /// Signal Point는 고려하지 않음
1135
        /// </summary>
1136
        /// <param name="symbol"></param>
1137
        /// <param name="_TargetItem"></param>
1138
        /// <param name="targetX"></param>
1139
        /// <param name="targetY"></param>
1140
        /// <returns></returns>
1141
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1142
        {
1143
            LMConnector tempConnector = null;
1144

    
1145
            List<Symbol> group = new List<Symbol>();
1146
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1147
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1148
            {
1149
                List<Connector> connectors = new List<Connector>();
1150
                foreach (var item in group)
1151
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1152
                /// Primary or Secondary Type Line만 고려
1153
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1154
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1155
                if (_connector != null)
1156
                {
1157
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1158
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1159
                    /// PipingPoint가 2개 이상만
1160
                    if (pointInfos.Count >= 2)
1161
                    {
1162
                        double lineX = 0;
1163
                        double lineY = 0;
1164
                        double length = 0;
1165
                        foreach (var item in pointInfos)
1166
                        {
1167
                            double tempX = item[1];
1168
                            double tempY = item[2];
1169

    
1170
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1171
                            if (calcDistance > length)
1172
                            {
1173
                                lineX = tempX;
1174
                                lineY = tempY;
1175
                            }
1176
                        }
1177

    
1178
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1179
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1180
                        placeRunInputs.AddPoint(-1, -1);
1181
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1182
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1183
                        if (tempConnector != null)
1184
                            tempConnector.Commit();
1185
                        ReleaseCOMObjects(_LMAItem);
1186
                        _LMAItem = null;
1187
                        ReleaseCOMObjects(placeRunInputs);
1188
                        placeRunInputs = null;
1189
                    }
1190
                }
1191
            }
1192

    
1193
            return tempConnector;
1194
        }
1195
        /// <summary>
1196
        /// Symbol의 PipingPoints를 구함
1197
        /// SignalPoint는 고려하지 않음
1198
        /// </summary>
1199
        /// <param name="symbol"></param>
1200
        /// <returns></returns>
1201
        private List<double[]> getPipingPoints(LMSymbol symbol)
1202
        {
1203
            LMModelItem modelItem = symbol.ModelItemObject;
1204
            LMPipingPoints pipingPoints = null;
1205
            if (modelItem.get_ItemTypeName() == "PipingComp")
1206
            {
1207
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1208
                pipingPoints = pipingComp.PipingPoints;
1209
                ReleaseCOMObjects(pipingComp);
1210
                pipingComp = null;
1211
            }
1212
            else if (modelItem.get_ItemTypeName() == "Instrument")
1213
            {
1214
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1215
                pipingPoints = instrument.PipingPoints;
1216
                ReleaseCOMObjects(instrument);
1217
                instrument = null;
1218
            }
1219
            else
1220
                Log.Write("다른 Type");
1221

    
1222
            List<double[]> info = new List<double[]>();
1223
            if (pipingPoints != null)
1224
            {
1225
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1226
                {
1227
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1228
                    {
1229
                        if (attribute.Name == "PipingPointNumber")
1230
                        {
1231
                            int index = Convert.ToInt32(attribute.get_Value());
1232
                            if (info.Find(loopX => loopX[0] == index) == null)
1233
                            {
1234
                                double x = 0;
1235
                                double y = 0;
1236
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1237
                                    info.Add(new double[] { index, x, y });
1238
                            }
1239
                        }
1240
                    }
1241
                }
1242
            }
1243
            ReleaseCOMObjects(modelItem);
1244
            modelItem = null;
1245
            ReleaseCOMObjects(pipingPoints);
1246
            pipingPoints = null;
1247

    
1248
            return info;
1249
        }
1250

    
1251
        private void RemoveSymbol(Symbol symbol)
1252
        {
1253
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1254
            {
1255
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1256
                if (_LMSymbol != null)
1257
                {
1258
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1259
                    ReleaseCOMObjects(_LMSymbol);
1260
                }
1261
            }
1262

    
1263
            symbol.SPPID.RepresentationId = string.Empty;
1264
            symbol.SPPID.ModelItemID = string.Empty;
1265
            symbol.SPPID.SPPID_X = double.NaN;
1266
            symbol.SPPID.SPPID_Y = double.NaN;
1267
            symbol.SPPID.SPPID_Min_X = double.NaN;
1268
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1269
            symbol.SPPID.SPPID_Max_X = double.NaN;
1270
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1271
        }
1272

    
1273
        private void RemoveSymbol(List<Symbol> symbols)
1274
        {
1275
            foreach (var symbol in symbols)
1276
            {
1277
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1278
                {
1279
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1280
                    if (_LMSymbol != null)
1281
                    {
1282
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1283
                        ReleaseCOMObjects(_LMSymbol);
1284
                    }
1285
                }
1286

    
1287
                symbol.SPPID.RepresentationId = string.Empty;
1288
                symbol.SPPID.ModelItemID = string.Empty;
1289
                symbol.SPPID.SPPID_X = double.NaN;
1290
                symbol.SPPID.SPPID_Y = double.NaN;
1291
                symbol.SPPID.SPPID_Min_X = double.NaN;
1292
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1293
                symbol.SPPID.SPPID_Max_X = double.NaN;
1294
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1295
            }
1296
        }
1297

    
1298
        /// <summary>
1299
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1300
        /// </summary>
1301
        /// <param name="targetConnector"></param>
1302
        /// <param name="targetSymbol"></param>
1303
        /// <param name="x"></param>
1304
        /// <param name="y"></param>
1305
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1306
        {
1307
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1308

    
1309
            double[] range = null;
1310
            List<double[]> points = new List<double[]>();
1311
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1312
            double x1 = range[0];
1313
            double y1 = range[1];
1314
            double x2 = range[2];
1315
            double y2 = range[3];
1316

    
1317
            // Origin 기준 Connector의 위치차이
1318
            double sceneX = 0;
1319
            double sceneY = 0;
1320
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1321
            double originX = 0;
1322
            double originY = 0;
1323
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1324
            double gapX = originX - sceneX;
1325
            double gapY = originY - sceneY;
1326

    
1327
            // SPPID Symbol과 ID2 심볼의 크기 차이
1328
            double sizeWidth = 0;
1329
            double sizeHeight = 0;
1330
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1331
            if (sizeWidth == 0 || sizeHeight == 0)
1332
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1333

    
1334
            double percentX = (x2 - x1) / sizeWidth;
1335
            double percentY = (y2 - y1) / sizeHeight;
1336

    
1337
            double SPPIDgapX = gapX * percentX;
1338
            double SPPIDgapY = gapY * percentY;
1339

    
1340
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1341
            double distance = double.MaxValue;
1342
            double[] resultPoint;
1343
            foreach (var point in points)
1344
            {
1345
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1346
                if (distance > result)
1347
                {
1348
                    distance = result;
1349
                    resultPoint = point;
1350
                    x = point[0];
1351
                    y = point[1];
1352
                }
1353
            }
1354

    
1355
            ReleaseCOMObjects(_TargetItem);
1356
        }
1357

    
1358
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1359
        {
1360
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1361
            if (index == 0)
1362
            {
1363
                x = targetLine.SPPID.START_X;
1364
                y = targetLine.SPPID.START_Y;
1365
            }
1366
            else
1367
            {
1368
                x = targetLine.SPPID.END_X;
1369
                y = targetLine.SPPID.END_Y;
1370
            }
1371
        }
1372

    
1373
        /// <summary>
1374
        /// SPPID Symbol의 Range를 구한다.
1375
        /// </summary>
1376
        /// <param name="symbol"></param>
1377
        /// <param name="range"></param>
1378
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1379
        {
1380
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1381
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1382
            double x1 = 0;
1383
            double y1 = 0;
1384
            double x2 = 0;
1385
            double y2 = 0;
1386
            symbol2d.Range(out x1, out y1, out x2, out y2);
1387
            range = new double[] { x1, y1, x2, y2 };
1388

    
1389
            for (int i = 1; i < int.MaxValue; i++)
1390
            {
1391
                double connX = 0;
1392
                double connY = 0;
1393
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1394
                    points.Add(new double[] { connX, connY });
1395
                else
1396
                    break;
1397
            }
1398

    
1399
            foreach (var childSymbol in symbol.ChildSymbols)
1400
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1401

    
1402
            ReleaseCOMObjects(_TargetItem);
1403
        }
1404

    
1405
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1406
        {
1407
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1408
            if (_TargetItem != null)
1409
            {
1410
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1411
                double x1 = 0;
1412
                double y1 = 0;
1413
                double x2 = 0;
1414
                double y2 = 0;
1415
                if (!bForGraphic)
1416
                {
1417
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1418
                    range = new double[] { x1, y1, x2, y2 };
1419
                }
1420
                else
1421
                {
1422
                    x1 = double.MaxValue;
1423
                    y1 = double.MaxValue;
1424
                    x2 = double.MinValue;
1425
                    y2 = double.MinValue;
1426
                    range = new double[] { x1, y1, x2, y2 };
1427

    
1428
                    foreach (var item in symbol2d.DrawingObjects)
1429
                    {
1430
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1431
                        {
1432
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1433
                            if (rangeObject.Layer == "Default")
1434
                            {
1435
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1436
                                range = new double[] {
1437
                                Math.Min(x1, range[0]),
1438
                                Math.Min(y1, range[1]),
1439
                                Math.Max(x2, range[2]),
1440
                                Math.Max(y2, range[3])
1441
                            };
1442
                            }
1443
                        }
1444
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1445
                        {
1446
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1447
                            if (rangeObject.Layer == "Default")
1448
                            {
1449
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1450
                                range = new double[] {
1451
                                Math.Min(x1, range[0]),
1452
                                Math.Min(y1, range[1]),
1453
                                Math.Max(x2, range[2]),
1454
                                Math.Max(y2, range[3])
1455
                            };
1456
                            }
1457
                        }
1458
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1459
                        {
1460
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1461
                            if (rangeObject.Layer == "Default")
1462
                            {
1463
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1464
                                range = new double[] {
1465
                                Math.Min(x1, range[0]),
1466
                                Math.Min(y1, range[1]),
1467
                                Math.Max(x2, range[2]),
1468
                                Math.Max(y2, range[3])
1469
                            };
1470
                            }
1471
                        }
1472
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1473
                        {
1474
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1475
                            if (rangeObject.Layer == "Default")
1476
                            {
1477
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1478
                                range = new double[] {
1479
                                Math.Min(x1, range[0]),
1480
                                Math.Min(y1, range[1]),
1481
                                Math.Max(x2, range[2]),
1482
                                Math.Max(y2, range[3])
1483
                            };
1484
                            }
1485
                        }
1486
                    }
1487
                }
1488

    
1489
                if (!bOnlySymbol)
1490
                {
1491
                    foreach (var childSymbol in symbol.ChildSymbols)
1492
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1493
                }
1494
                ReleaseCOMObjects(_TargetItem);
1495
            }
1496
        }
1497

    
1498
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1499
        {
1500
            if (labelPersist != null)
1501
            {
1502
                double x1 = double.MaxValue;
1503
                double y1 = double.MaxValue;
1504
                double x2 = double.MinValue;
1505
                double y2 = double.MinValue;
1506
                range = new double[] { x1, y1, x2, y2 };
1507

    
1508
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1509
                foreach (var item in dependency.DrawingObjects)
1510
                {
1511
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1512
                    if (textBox != null)
1513
                    {
1514
                        if (dependency != null)
1515
                        {
1516
                            double tempX1;
1517
                            double tempY1;
1518
                            double tempX2;
1519
                            double tempY2;
1520
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1521
                            x1 = Math.Min(x1, tempX1);
1522
                            y1 = Math.Min(y1, tempY1);
1523
                            x2 = Math.Max(x2, tempX2);
1524
                            y2 = Math.Max(y2, tempY2);
1525

    
1526
                            range = new double[] { x1, y1, x2, y2 };
1527
                        }
1528
                    }
1529
                }
1530
                
1531
            }
1532
        }
1533

    
1534
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1535
        {
1536
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1537
            foreach (var symbol in symbols)
1538
            {
1539
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1540
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1541
                double x1 = 0;
1542
                double y1 = 0;
1543
                double x2 = 0;
1544
                double y2 = 0;
1545
                symbol2d.Range(out x1, out y1, out x2, out y2);
1546

    
1547
                tempRange[0] = Math.Min(tempRange[0], x1);
1548
                tempRange[1] = Math.Min(tempRange[1], y1);
1549
                tempRange[2] = Math.Max(tempRange[2], x2);
1550
                tempRange[3] = Math.Max(tempRange[3], y2);
1551

    
1552
                foreach (var childSymbol in symbol.ChildSymbols)
1553
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1554

    
1555
                ReleaseCOMObjects(_TargetItem);
1556
            }
1557

    
1558
            range = tempRange;
1559
        }
1560

    
1561
        /// <summary>
1562
        /// Child Modeling 된 Symbol의 Range를 구한다.
1563
        /// </summary>
1564
        /// <param name="childSymbol"></param>
1565
        /// <param name="range"></param>
1566
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1567
        {
1568
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1569
            if (_ChildSymbol != null)
1570
            {
1571
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1572
                double x1 = 0;
1573
                double y1 = 0;
1574
                double x2 = 0;
1575
                double y2 = 0;
1576
                symbol2d.Range(out x1, out y1, out x2, out y2);
1577
                range[0] = Math.Min(range[0], x1);
1578
                range[1] = Math.Min(range[1], y1);
1579
                range[2] = Math.Max(range[2], x2);
1580
                range[3] = Math.Max(range[3], y2);
1581

    
1582
                for (int i = 1; i < int.MaxValue; i++)
1583
                {
1584
                    double connX = 0;
1585
                    double connY = 0;
1586
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1587
                        points.Add(new double[] { connX, connY });
1588
                    else
1589
                        break;
1590
                }
1591

    
1592
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1593
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1594

    
1595
                ReleaseCOMObjects(_ChildSymbol);
1596
            }
1597
        }
1598

    
1599
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1600
        {
1601
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1602
            if (_ChildSymbol != null)
1603
            {
1604
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1605
                double x1 = 0;
1606
                double y1 = 0;
1607
                double x2 = 0;
1608
                double y2 = 0;
1609
                symbol2d.Range(out x1, out y1, out x2, out y2);
1610
                range[0] = Math.Min(range[0], x1);
1611
                range[1] = Math.Min(range[1], y1);
1612
                range[2] = Math.Max(range[2], x2);
1613
                range[3] = Math.Max(range[3], y2);
1614

    
1615
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1616
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1617
                ReleaseCOMObjects(_ChildSymbol);
1618
            }
1619
        }
1620

    
1621
        /// <summary>
1622
        /// Label Symbol Modeling
1623
        /// </summary>
1624
        /// <param name="symbol"></param>
1625
        private void LabelSymbolModeling(Symbol symbol)
1626
        {
1627
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1628
            {
1629
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1630
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1631
                    return;
1632
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1633

    
1634
                string symbolUID = itemAttribute.VALUE;
1635
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1636
                if (targetItem != null &&
1637
                    (targetItem.GetType() == typeof(Symbol) ||
1638
                    targetItem.GetType() == typeof(Equipment)))
1639
                {
1640
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1641
                    string sRep = null;
1642
                    if (targetItem.GetType() == typeof(Symbol))
1643
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1644
                    else if (targetItem.GetType() == typeof(Equipment))
1645
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1646
                    if (!string.IsNullOrEmpty(sRep))
1647
                    {
1648
                        // LEADER Line 검사
1649
                        bool leaderLine = false;
1650
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1651
                        if (symbolMapping != null)
1652
                            leaderLine = symbolMapping.LEADERLINE;
1653

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

    
1658
                        //Leader 선 센터로
1659
                        if (_LMLabelPresist != null)
1660
                        {
1661
                            // Target Item에 Label의 Attribute Input
1662
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1663

    
1664
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1665
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1666
                            if (dependency != null)
1667
                            {
1668
                                bool result = false;
1669
                                foreach (var attributes in dependency.AttributeSets)
1670
                                {
1671
                                    foreach (var attribute in attributes)
1672
                                    {
1673
                                        string name = attribute.Name;
1674
                                        string value = attribute.GetValue().ToString();
1675
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1676
                                        {
1677
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1678
                                            {
1679
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1680
                                                {
1681
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1682
                                                    double prevX = _TargetItem.get_XCoordinate();
1683
                                                    double prevY = _TargetItem.get_YCoordinate();
1684
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1685
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1686
                                                    result = true;
1687
                                                    break;
1688
                                                }
1689
                                            }
1690
                                        }
1691

    
1692
                                        if (result)
1693
                                            break;
1694
                                    }
1695

    
1696
                                    if (result)
1697
                                        break;
1698
                                }
1699
                            }
1700

    
1701
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1702
                            _LMLabelPresist.Commit();
1703
                            ReleaseCOMObjects(_LMLabelPresist);
1704
                        }
1705

    
1706
                        ReleaseCOMObjects(_TargetItem);
1707
                    }
1708
                }
1709
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1710
                {
1711
                    Line targetLine = targetItem as Line;
1712
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1713
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1714
                    if (connectedLMConnector != null)
1715
                    {
1716
                        // LEADER Line 검사
1717
                        bool leaderLine = false;
1718
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1719
                        if (symbolMapping != null)
1720
                            leaderLine = symbolMapping.LEADERLINE;
1721

    
1722
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1723
                        if (_LMLabelPresist != null)
1724
                        {
1725
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1726
                            _LMLabelPresist.Commit();
1727
                            ReleaseCOMObjects(_LMLabelPresist);
1728
                        }
1729
                        ReleaseCOMObjects(connectedLMConnector);
1730
                    }
1731

    
1732
                    foreach (var item in connectorVertices)
1733
                        if (item.Key != null)
1734
                            ReleaseCOMObjects(item.Key);
1735
                }
1736
            }
1737
        }
1738

    
1739
        /// <summary>
1740
        /// Equipment를 실제로 Modeling 메서드
1741
        /// </summary>
1742
        /// <param name="equipment"></param>
1743
        private void EquipmentModeling(Equipment equipment)
1744
        {
1745
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1746
                return;
1747

    
1748
            LMSymbol _LMSymbol = null;
1749
            LMSymbol targetItem = null;
1750
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1751
            double x = equipment.SPPID.ORIGINAL_X;
1752
            double y = equipment.SPPID.ORIGINAL_Y;
1753
            int mirror = 0;
1754
            double angle = equipment.ANGLE;
1755

    
1756
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1757

    
1758
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1759
            if (connector != null)
1760
            {
1761
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1762
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1763
                if (connEquipment != null)
1764
                {
1765
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1766
                        EquipmentModeling(connEquipment);
1767

    
1768
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1769
                    {
1770
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1771
                        if (targetItem != null)
1772
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1773
                        else
1774
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1775
                    }
1776
                    else
1777
                    {
1778
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1779
                    }
1780
                }
1781
                else if (connVendorPackage != null)
1782
                {
1783
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
1784
                    {
1785
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
1786
                        if (targetItem != null)
1787
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1788
                        else
1789
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1790
                    }
1791
                }
1792
                else
1793
                {
1794
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1795
                }
1796
            }
1797
            else
1798
            {
1799
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1800
            }
1801

    
1802
            if (_LMSymbol != null)
1803
            {
1804
                _LMSymbol.Commit();
1805
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1806
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1807
                ReleaseCOMObjects(_LMSymbol);
1808
            }
1809

    
1810
            if (targetItem != null)
1811
            {
1812
                ReleaseCOMObjects(targetItem);
1813
            }
1814

    
1815
            ReleaseCOMObjects(_LMSymbol);
1816
        }
1817

    
1818
        private void VendorPackageModeling(VendorPackage vendorPackage)
1819
        {
1820
            ETCSetting setting = ETCSetting.GetInstance();
1821
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
1822
            {
1823
                string symbolPath = setting.VendorPackageSymbolPath;
1824
                double x = vendorPackage.SPPID.ORIGINAL_X;
1825
                double y = vendorPackage.SPPID.ORIGINAL_Y;
1826

    
1827
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
1828
                if (symbol != null)
1829
                {
1830
                    symbol.Commit();
1831
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
1832
                }
1833

    
1834
                ReleaseCOMObjects(symbol);
1835
                symbol = null;
1836
            }
1837
        }
1838

    
1839
        /// <summary>
1840
        /// 첫 진입점
1841
        /// </summary>
1842
        /// <param name="symbol"></param>
1843
        private void SymbolModelingBySymbol(Symbol symbol)
1844
        {
1845
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1846
            List<object> endObjects = new List<object>();
1847
            endObjects.Add(symbol);
1848

    
1849
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1850
            foreach (var connector in symbol.CONNECTORS)
1851
            {
1852
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1853
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1854
                {
1855
                    endObjects.Add(connItem);
1856
                    if (connItem.GetType() == typeof(Symbol))
1857
                    {
1858
                        Symbol connSymbol = connItem as Symbol;
1859
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1860
                        {
1861
                            SymbolModeling(connSymbol, symbol);
1862
                        }
1863
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1864
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1865
                    }
1866
                    else if (connItem.GetType() == typeof(Line))
1867
                    {
1868
                        Line connLine = connItem as Line;
1869
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1870
                    }
1871
                }
1872
            }
1873
        }
1874

    
1875
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1876
        {
1877
            foreach (var connector in symbol.CONNECTORS)
1878
            {
1879
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1880
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1881
                {
1882
                    if (!endObjects.Contains(connItem))
1883
                    {
1884
                        endObjects.Add(connItem);
1885
                        if (connItem.GetType() == typeof(Symbol))
1886
                        {
1887
                            Symbol connSymbol = connItem as Symbol;
1888
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1889
                            {
1890
                                SymbolModeling(connSymbol, symbol);
1891
                            }
1892
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1893
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1894
                        }
1895
                        else if (connItem.GetType() == typeof(Line))
1896
                        {
1897
                            Line connLine = connItem as Line;
1898
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1899
                        }
1900
                    }
1901
                }
1902
            }
1903
        }
1904

    
1905
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1906
        {
1907
            foreach (var connector in line.CONNECTORS)
1908
            {
1909
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1910
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1911
                {
1912
                    if (!endObjects.Contains(connItem))
1913
                    {
1914
                        endObjects.Add(connItem);
1915
                        if (connItem.GetType() == typeof(Symbol))
1916
                        {
1917
                            Symbol connSymbol = connItem as Symbol;
1918
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1919
                            {
1920
                                List<Symbol> group = new List<Symbol>();
1921
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1922
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1923
                                List<Symbol> endModelingGroup = new List<Symbol>();
1924
                                if (priority != null)
1925
                                {
1926
                                    SymbolGroupModeling(priority, group);
1927

    
1928
                                    // Range 겹치는지 확인해야함
1929
                                    double[] prevRange = null;
1930
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1931
                                    double[] groupRange = null;
1932
                                    GetSPPIDSymbolRange(group, ref groupRange);
1933

    
1934
                                    double distanceX = 0;
1935
                                    double distanceY = 0;
1936
                                    bool overlapX = false;
1937
                                    bool overlapY = false;
1938
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1939
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1940
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1941
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1942
                                    {
1943
                                        RemoveSymbol(group);
1944
                                        foreach (var _temp in group)
1945
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1946

    
1947
                                        SymbolGroupModeling(priority, group);
1948
                                    }
1949
                                }
1950
                                else
1951
                                {
1952
                                    SymbolModeling(connSymbol, null);
1953
                                    // Range 겹치는지 확인해야함
1954
                                    double[] prevRange = null;
1955
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1956
                                    double[] connRange = null;
1957
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1958

    
1959
                                    double distanceX = 0;
1960
                                    double distanceY = 0;
1961
                                    bool overlapX = false;
1962
                                    bool overlapY = false;
1963
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1964
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1965
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1966
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1967
                                    {
1968
                                        RemoveSymbol(connSymbol);
1969
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1970

    
1971
                                        SymbolModeling(connSymbol, null);
1972
                                    }
1973
                                }
1974
                            }
1975
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1976
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1977
                        }
1978
                        else if (connItem.GetType() == typeof(Line))
1979
                        {
1980
                            Line connLine = connItem as Line;
1981
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1982
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1983
                        }
1984
                    }
1985
                }
1986
            }
1987
        }
1988

    
1989
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1990
        {
1991
            List<Symbol> endModelingGroup = new List<Symbol>();
1992
            SymbolModeling(firstSymbol, null);
1993
            endModelingGroup.Add(firstSymbol);
1994
            while (endModelingGroup.Count != group.Count)
1995
            {
1996
                foreach (var _symbol in group)
1997
                {
1998
                    if (!endModelingGroup.Contains(_symbol))
1999
                    {
2000
                        foreach (var _connector in _symbol.CONNECTORS)
2001
                        {
2002
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2003
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2004
                            {
2005
                                SymbolModeling(_symbol, _connSymbol);
2006
                                endModelingGroup.Add(_symbol);
2007
                                break;
2008
                            }
2009
                        }
2010
                    }
2011
                }
2012
            }
2013
        }
2014

    
2015
        /// <summary>
2016
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2017
        /// </summary>
2018
        /// <param name="childSymbol"></param>
2019
        /// <param name="parentSymbol"></param>
2020
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2021
        {
2022
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2023
            double x1 = 0;
2024
            double x2 = 0;
2025
            double y1 = 0;
2026
            double y2 = 0;
2027
            symbol2d.Range(out x1, out y1, out x2, out y2);
2028

    
2029
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2030
            if (_LMSymbol != null)
2031
            {
2032
                _LMSymbol.Commit();
2033
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2034
                foreach (var item in childSymbol.ChildSymbols)
2035
                    CreateChildSymbol(item, _LMSymbol, parent);
2036
            }
2037

    
2038

    
2039
            ReleaseCOMObjects(_LMSymbol);
2040
        }
2041
        double index = 0;
2042
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2043
        {
2044
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2045
                return;
2046

    
2047
            List<Line> group = new List<Line>();
2048
            GetConnectedLineGroup(line, group);
2049
            LineCoordinateCorrection(group);
2050

    
2051
            foreach (var groupLine in group)
2052
            {
2053
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2054
                {
2055
                    BranchLines.Add(groupLine);
2056
                    continue;
2057
                }
2058

    
2059
                bool diagonal = false;
2060
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2061
                    diagonal = true;
2062
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2063
                LMSymbol _LMSymbolStart = null;
2064
                LMSymbol _LMSymbolEnd = null;
2065
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2066
                foreach (var connector in groupLine.CONNECTORS)
2067
                {
2068
                    double x = 0;
2069
                    double y = 0;
2070
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2071
                    if (connector.ConnectedObject == null)
2072
                    {
2073
                        placeRunInputs.AddPoint(x, y);
2074
                    }
2075
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2076
                    {
2077
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2078
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2079
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2080
                        {
2081
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2082
                            if (_LMSymbolStart != null)
2083
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2084
                            else
2085
                                placeRunInputs.AddPoint(x, y);
2086
                        }
2087
                        else
2088
                        {
2089
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2090
                            if (_LMSymbolEnd != null)
2091
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2092
                            else
2093
                                placeRunInputs.AddPoint(x, y);
2094
                        }
2095
                    }
2096
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2097
                    {
2098
                        Line targetLine = connector.ConnectedObject as Line;
2099
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2100
                        {
2101
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2102
                            if (targetConnector != null)
2103
                            {
2104
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2105
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2106
                            }
2107
                            else
2108
                            {
2109
                                placeRunInputs.AddPoint( x, y);
2110
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2111
                            }
2112
                        }
2113
                        else
2114
                        {
2115
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2116
                            {
2117
                                index += 0.01;
2118
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2119
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2120
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2121
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2122
                                else
2123
                                {
2124
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2125
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2126
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2127
                                    else
2128
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2129
                                }
2130
                            }
2131

    
2132
                            placeRunInputs.AddPoint(x, y);
2133

    
2134
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2135
                            {
2136
                                index += 0.01;
2137
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2138
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2139
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2140
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2141
                                else
2142
                                {
2143
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2144
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2145
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2146
                                    else
2147
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2148
                                }
2149
                            }
2150
                        }
2151
                    }
2152
                }
2153

    
2154
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2155
                if (_lMConnector != null)
2156
                {
2157
                    _lMConnector.Commit();
2158
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2159

    
2160
                    bool bRemodelingStart = false;
2161
                    if (_LMSymbolStart != null)
2162
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2163
                    bool bRemodelingEnd = false;
2164
                    if (_LMSymbolEnd != null)
2165
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2166

    
2167
                    if (bRemodelingStart || bRemodelingEnd)
2168
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2169

    
2170
                    FlowMarkModeling(groupLine);
2171
                    LineNumberModelingOnlyOne(groupLine);
2172

    
2173
                    ReleaseCOMObjects(_lMConnector);
2174

    
2175
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2176
                    if (modelItem != null)
2177
                    {
2178
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2179
                        if (attribute != null)
2180
                            attribute.set_Value("End 1 is upstream (Inlet)");
2181
                        modelItem.Commit();
2182
                    }
2183
                    ReleaseCOMObjects(modelItem);
2184
                    modelItem = null;
2185
                }
2186
                else if (!isBranchModeling)
2187
                {
2188
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2189
                }
2190

    
2191
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2192
                x.ConnectedObject != null &&
2193
                x.ConnectedObject.GetType() == typeof(Line) &&
2194
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2195
                .Select(x => x.ConnectedObject)
2196
                .ToList();
2197

    
2198
                foreach (var item in removeLines)
2199
                    RemoveLineForModeling(item as Line);
2200

    
2201
                if (_LMAItem != null)
2202
                    ReleaseCOMObjects(_LMAItem);
2203
                if (placeRunInputs != null)
2204
                    ReleaseCOMObjects(placeRunInputs);
2205
                if (_LMSymbolStart != null)
2206
                    ReleaseCOMObjects(_LMSymbolStart);
2207
                if (_LMSymbolEnd != null)
2208
                    ReleaseCOMObjects(_LMSymbolEnd);
2209

    
2210
                if (isBranchModeling && BranchLines.Contains(groupLine))
2211
                    BranchLines.Remove(groupLine);
2212
            }
2213
        }
2214

    
2215
        private void RemoveLineForModeling(Line line)
2216
        {
2217
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2218
            if (modelItem != null)
2219
            {
2220
                foreach (LMRepresentation rep in modelItem.Representations)
2221
                {
2222
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2223
                    {
2224
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2225
                        dynamic OID = rep.get_GraphicOID().ToString();
2226
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2227
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2228
                        int verticesCount = lineStringGeometry.VertexCount;
2229
                        double[] vertices = null;
2230
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2231
                        for (int i = 0; i < verticesCount; i++)
2232
                        {
2233
                            double x = 0;
2234
                            double y = 0;
2235
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2236
                            if (verticesCount == 2 && (x < 0 || y < 0))
2237
                                _placement.PIDRemovePlacement(rep);
2238
                        }
2239
                        ReleaseCOMObjects(_LMConnector);
2240
                    }
2241
                }
2242

    
2243
                ReleaseCOMObjects(modelItem);
2244
            }
2245
        }
2246

    
2247
        private void GetConnectedLineGroup(Line line, List<Line> group)
2248
        {
2249
            if (!group.Contains(line))
2250
                group.Add(line);
2251
            foreach (var connector in line.CONNECTORS)
2252
            {
2253
                if (connector.ConnectedObject != null &&
2254
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2255
                    !group.Contains(connector.ConnectedObject) &&
2256
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2257
                {
2258
                    Line connLine = connector.ConnectedObject as Line;
2259
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2260
                    {
2261
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2262
                            group.Insert(0, connLine);
2263
                        else
2264
                            group.Add(connLine);
2265
                        GetConnectedLineGroup(connLine, group);
2266
                    }
2267
                }
2268
            }
2269
        }
2270

    
2271
        private void LineCoordinateCorrection(List<Line> group)
2272
        {
2273
            // 순서대로 전 Item 기준 정렬
2274
            LineCoordinateCorrectionByStart(group);
2275

    
2276
            // 역으로 심볼이 있을 경우 좌표 보정
2277
            LineCoordinateCorrectionForLastLine(group);
2278
        }
2279

    
2280
        private void LineCoordinateCorrectionByStart(List<Line> group)
2281
        {
2282
            for (int i = 0; i < group.Count; i++)
2283
            {
2284
                Line line = group[i];
2285
                if (i == 0)
2286
                {
2287
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2288
                    if (symbolConnector != null)
2289
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2290
                }
2291
                else if (i != 0)
2292
                {
2293
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2294
                }
2295
            }
2296
        }
2297

    
2298
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2299
        {
2300
            Line checkLine = group[group.Count - 1];
2301
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2302
            if (lastSymbolConnector != null)
2303
            {
2304
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2305
                for (int i = group.Count - 2; i >= 0; i--)
2306
                {
2307
                    Line line = group[i + 1];
2308
                    Line prevLine = group[i];
2309

    
2310
                    // 같으면 보정
2311
                    if (line.SlopeType == prevLine.SlopeType)
2312
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2313
                    else
2314
                    {
2315
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2316
                        {
2317
                            double prevX = 0;
2318
                            double prevY = 0;
2319
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2320
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2321

    
2322
                            double x = 0;
2323
                            double y = 0;
2324
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2325
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2326
                        }
2327
                        else if (line.SlopeType == SlopeType.VERTICAL)
2328
                        {
2329
                            double prevX = 0;
2330
                            double prevY = 0;
2331
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2332
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2333

    
2334
                            double x = 0;
2335
                            double y = 0;
2336
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2337
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2338
                        }
2339
                        break;
2340
                    }
2341
                }
2342
            }
2343
        }
2344

    
2345
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2346
        {
2347
            double x = 0;
2348
            double y = 0;
2349
            if (connItem.GetType() == typeof(Symbol))
2350
            {
2351
                Symbol targetSymbol = connItem as Symbol;
2352
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2353
                if (targetConnector != null)
2354
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2355
                else
2356
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2357
            }
2358
            else if (connItem.GetType() == typeof(Line))
2359
            {
2360
                Line targetLine = connItem as Line;
2361
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2362
            }
2363

    
2364
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2365
        }
2366

    
2367
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2368
        {
2369
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2370
            int index = line.CONNECTORS.IndexOf(connector);
2371
            if (index == 0)
2372
            {
2373
                line.SPPID.START_X = x;
2374
                line.SPPID.START_Y = y;
2375
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2376
                    line.SPPID.END_Y = y;
2377
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2378
                    line.SPPID.END_X = x;
2379
            }
2380
            else
2381
            {
2382
                line.SPPID.END_X = x;
2383
                line.SPPID.END_Y = y;
2384
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2385
                    line.SPPID.START_Y = y;
2386
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2387
                    line.SPPID.START_X = x;
2388
            }
2389
        }
2390

    
2391
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2392
        {
2393
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2394
            int index = line.CONNECTORS.IndexOf(connector);
2395
            if (index == 0)
2396
            {
2397
                line.SPPID.START_X = x;
2398
                if (line.SlopeType == SlopeType.VERTICAL)
2399
                    line.SPPID.END_X = x;
2400
            }
2401
            else
2402
            {
2403
                line.SPPID.END_X = x;
2404
                if (line.SlopeType == SlopeType.VERTICAL)
2405
                    line.SPPID.START_X = x;
2406
            }
2407
        }
2408

    
2409
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2410
        {
2411
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2412
            int index = line.CONNECTORS.IndexOf(connector);
2413
            if (index == 0)
2414
            {
2415
                line.SPPID.START_Y = y;
2416
                if (line.SlopeType == SlopeType.HORIZONTAL)
2417
                    line.SPPID.END_Y = y;
2418
            }
2419
            else
2420
            {
2421
                line.SPPID.END_Y = y;
2422
                if (line.SlopeType == SlopeType.HORIZONTAL)
2423
                    line.SPPID.START_Y = y;
2424
            }
2425
        }
2426

    
2427
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2428
        {
2429
            if (symbol != null)
2430
            {
2431
                string repID = symbol.AsLMRepresentation().Id;
2432
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2433
                string lineUID = line.UID;
2434

    
2435
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2436
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2437
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2438

    
2439
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2440
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2441
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2442

    
2443
                if (startSpecBreak != null || startEndBreak != null)
2444
                    result = true;
2445
            }
2446
        }
2447

    
2448
        /// <summary>
2449
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2450
        /// </summary>
2451
        /// <param name="lines"></param>
2452
        /// <param name="prevLMConnector"></param>
2453
        /// <param name="startSymbol"></param>
2454
        /// <param name="endSymbol"></param>
2455
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2456
        {
2457
            string symbolPath = string.Empty;
2458
            #region get symbol path
2459
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2460
            symbolPath = GetSPPIDFileName(modelItem);
2461
            ReleaseCOMObjects(modelItem);
2462
            #endregion
2463
            bool diagonal = false;
2464
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2465
                diagonal = true;
2466
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2467
            LMConnector newConnector = null;
2468
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2469
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2470
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2471
            int verticesCount = lineStringGeometry.VertexCount;
2472
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2473

    
2474
            List<double[]> vertices = new List<double[]>();
2475
            for (int i = 1; i <= verticesCount; i++)
2476
            {
2477
                double x = 0;
2478
                double y = 0;
2479
                lineStringGeometry.GetVertex(i, ref x, ref y);
2480
                vertices.Add(new double[] { x, y });
2481
            }
2482

    
2483
            for (int i = 0; i < vertices.Count; i++)
2484
            {
2485
                double[] points = vertices[i];
2486
                // 시작 심볼이 있고 첫번째 좌표일 때
2487
                if (startSymbol != null && i == 0)
2488
                {
2489
                    if (bStart)
2490
                    {
2491
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2492
                        if (slopeType == SlopeType.HORIZONTAL)
2493
                            placeRunInputs.AddPoint(points[0], -0.1);
2494
                        else if (slopeType == SlopeType.VERTICAL)
2495
                            placeRunInputs.AddPoint(-0.1, points[1]);
2496
                        else
2497
                            placeRunInputs.AddPoint(points[0], -0.1);
2498

    
2499
                        placeRunInputs.AddPoint(points[0], points[1]);
2500
                    }
2501
                    else
2502
                    {
2503
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2504
                    }
2505
                }
2506
                // 마지막 심볼이 있고 마지막 좌표일 때
2507
                else if (endSymbol != null && i == vertices.Count - 1)
2508
                {
2509
                    if (bEnd)
2510
                    {
2511
                        placeRunInputs.AddPoint(points[0], points[1]);
2512

    
2513
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2514
                        if (slopeType == SlopeType.HORIZONTAL)
2515
                            placeRunInputs.AddPoint(points[0], -0.1);
2516
                        else if (slopeType == SlopeType.VERTICAL)
2517
                            placeRunInputs.AddPoint(-0.1, points[1]);
2518
                        else
2519
                            placeRunInputs.AddPoint(points[0], -0.1);
2520
                    }
2521
                    else
2522
                    {
2523
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2524
                    }
2525
                }
2526
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2527
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2528
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2529
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2530
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2531
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2532
                else
2533
                    placeRunInputs.AddPoint(points[0], points[1]);
2534
            }
2535

    
2536
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2537
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2538

    
2539
            ReleaseCOMObjects(placeRunInputs);
2540
            ReleaseCOMObjects(_LMAItem);
2541
            ReleaseCOMObjects(modelItem);
2542

    
2543
            if (newConnector != null)
2544
            {
2545
                newConnector.Commit();
2546
                if (startSymbol != null && bStart)
2547
                {
2548
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2549
                    placeRunInputs = new PlaceRunInputs();
2550
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2551
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2552
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2553
                    if (_LMConnector != null)
2554
                    {
2555
                        _LMConnector.Commit();
2556
                        RemoveConnectorForReModelingLine(newConnector);
2557
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2558
                        ReleaseCOMObjects(_LMConnector);
2559
                    }
2560
                    ReleaseCOMObjects(placeRunInputs);
2561
                    ReleaseCOMObjects(_LMAItem);
2562
                }
2563

    
2564
                if (endSymbol != null && bEnd)
2565
                {
2566
                    if (startSymbol != null)
2567
                    {
2568
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2569
                        newConnector = dicVertices.First().Key;
2570
                    }
2571

    
2572
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2573
                    placeRunInputs = new PlaceRunInputs();
2574
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2575
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2576
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2577
                    if (_LMConnector != null)
2578
                    {
2579
                        _LMConnector.Commit();
2580
                        RemoveConnectorForReModelingLine(newConnector);
2581
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2582
                        ReleaseCOMObjects(_LMConnector);
2583
                    }
2584
                    ReleaseCOMObjects(placeRunInputs);
2585
                    ReleaseCOMObjects(_LMAItem);
2586
                }
2587

    
2588
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2589
                ReleaseCOMObjects(newConnector);
2590
            }
2591

    
2592
            ReleaseCOMObjects(modelItem);
2593
        }
2594

    
2595
        /// <summary>
2596
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2597
        /// </summary>
2598
        /// <param name="connector"></param>
2599
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2600
        {
2601
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2602
            foreach (var item in dicVertices)
2603
            {
2604
                if (item.Value.Count == 2)
2605
                {
2606
                    bool result = false;
2607
                    foreach (var point in item.Value)
2608
                    {
2609
                        if (point[0] < 0 || point[1] < 0)
2610
                        {
2611
                            result = true;
2612
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2613
                            break;
2614
                        }
2615
                    }
2616

    
2617
                    if (result)
2618
                        break;
2619
                }
2620
            }
2621
            foreach (var item in dicVertices)
2622
                ReleaseCOMObjects(item.Key);
2623
        }
2624

    
2625
        /// <summary>
2626
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2627
        /// </summary>
2628
        /// <param name="symbol"></param>
2629
        /// <param name="line"></param>
2630
        /// <returns></returns>
2631
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2632
        {
2633
            LMSymbol _LMSymbol = null;
2634
            foreach (var connector in symbol.CONNECTORS)
2635
            {
2636
                if (connector.CONNECTEDITEM == line.UID)
2637
                {
2638
                    if (connector.Index == 0)
2639
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2640
                    else
2641
                    {
2642
                        ChildSymbol child = null;
2643
                        foreach (var childSymbol in symbol.ChildSymbols)
2644
                        {
2645
                            if (childSymbol.Connectors.Contains(connector))
2646
                                child = childSymbol;
2647
                            else
2648
                                child = GetChildSymbolByConnector(childSymbol, connector);
2649

    
2650
                            if (child != null)
2651
                                break;
2652
                        }
2653

    
2654
                        if (child != null)
2655
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2656
                    }
2657

    
2658
                    break;
2659
                }
2660
            }
2661

    
2662
            return _LMSymbol;
2663
        }
2664

    
2665
        /// <summary>
2666
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2667
        /// </summary>
2668
        /// <param name="item"></param>
2669
        /// <param name="connector"></param>
2670
        /// <returns></returns>
2671
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2672
        {
2673
            foreach (var childSymbol in item.ChildSymbols)
2674
            {
2675
                if (childSymbol.Connectors.Contains(connector))
2676
                    return childSymbol;
2677
                else
2678
                    return GetChildSymbolByConnector(childSymbol, connector);
2679
            }
2680

    
2681
            return null;
2682
        }
2683

    
2684
        /// <summary>
2685
        /// EndBreak 모델링 메서드
2686
        /// </summary>
2687
        /// <param name="endBreak"></param>
2688
        private void EndBreakModeling(EndBreak endBreak)
2689
        {
2690
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2691
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2692

    
2693
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2694
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
2695
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2696

    
2697
            if (targetLMConnector != null)
2698
            {
2699
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2700
                Array array = null;
2701
                if (point != null)
2702
                    array = new double[] { 0, point[0], point[1] };
2703
                else
2704
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2705
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2706
                if (_LmLabelPersist != null)
2707
                {
2708
                    _LmLabelPersist.Commit();
2709
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2710
                    if (_LmLabelPersist.ModelItemObject != null)
2711
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2712
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2713
                    ReleaseCOMObjects(_LmLabelPersist);
2714
                }
2715
                ReleaseCOMObjects(targetLMConnector);
2716
            }
2717
            else
2718
            {
2719
                Log.Write("End Break UID : " + endBreak.UID);
2720
                Log.Write("Can't find targetLMConnector");
2721
            }
2722
        }
2723

    
2724
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
2725
        {
2726
            string symbolPath = string.Empty;
2727
            #region get symbol path
2728
            if (string.IsNullOrEmpty(changeSymbolPath))
2729
            {
2730
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2731
                symbolPath = GetSPPIDFileName(modelItem);
2732
                ReleaseCOMObjects(modelItem);
2733
            }
2734
            else
2735
                symbolPath = changeSymbolPath;
2736
            
2737
            #endregion
2738

    
2739
            LMConnector newConnector = null;
2740
            dynamic OID = connector.get_GraphicOID().ToString();
2741
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2742
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2743
            int verticesCount = lineStringGeometry.VertexCount;
2744
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2745
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2746

    
2747
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2748
            {
2749
                double[] vertices = null;
2750
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2751
                double x = 0;
2752
                double y = 0;
2753
                lineStringGeometry.GetVertex(1, ref x, ref y);
2754

    
2755
                string flowDirection = string.Empty;
2756
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2757
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2758
                    flowDirection = flowAttribute.get_Value().ToString();
2759

    
2760
                if (flowDirection == "End 1 is downstream (Outlet)")
2761
                {
2762
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2763
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2764
                    flowDirection = "End 1 is upstream (Inlet)";
2765
                }
2766
                else
2767
                {
2768
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2769
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2770
                }
2771
                string oldModelItemId = connector.ModelItemID;
2772
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2773
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2774
                newConnector.Commit();
2775
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2776
                if (!string.IsNullOrEmpty(flowDirection))
2777
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2778
                ReleaseCOMObjects(connector);
2779

    
2780
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
2781
                {
2782
                    foreach (var repId in line.SPPID.Representations)
2783
                    {
2784
                        LMConnector _connector = dataSource.GetConnector(repId);
2785
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
2786
                        {
2787
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
2788
                            {
2789
                                line.SPPID.ModelItemId = _connector.ModelItemID;
2790
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
2791
                            }
2792
                        }
2793
                        ReleaseCOMObjects(_connector);
2794
                        _connector = null;
2795
                    }
2796
                }
2797
            }
2798

    
2799
            return newConnector;
2800
        }
2801

    
2802
        /// <summary>
2803
        /// SpecBreak Modeling 메서드
2804
        /// </summary>
2805
        /// <param name="specBreak"></param>
2806
        private void SpecBreakModeling(SpecBreak specBreak)
2807
        {
2808
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2809
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2810

    
2811
            if (upStreamObj != null &&
2812
                downStreamObj != null)
2813
            {
2814
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2815
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && targetLMConnector != null)
2816
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2817

    
2818
                if (targetLMConnector != null)
2819
                {
2820
                    foreach (var attribute in specBreak.ATTRIBUTES)
2821
                    {
2822
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2823
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2824
                        {
2825
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2826
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2827
                            Array array = null;
2828
                            if (point != null)
2829
                                array = new double[] { 0, point[0], point[1] };
2830
                            else
2831
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2832
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2833

    
2834
                            if (_LmLabelPersist != null)
2835
                            {
2836
                                _LmLabelPersist.Commit();
2837
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2838
                                if (_LmLabelPersist.ModelItemObject != null)
2839
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2840
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2841
                                ReleaseCOMObjects(_LmLabelPersist);
2842
                            }
2843
                        }
2844
                    }
2845
                    ReleaseCOMObjects(targetLMConnector);
2846
                }
2847
                else
2848
                {
2849
                    Log.Write("Spec Break UID : " + specBreak.UID);
2850
                    Log.Write("Can't find targetLMConnector");
2851
                }
2852
            }
2853
        }
2854

    
2855
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2856
        {
2857
            LMConnector targetConnector = null;
2858
            Symbol targetSymbol = targetObj as Symbol;
2859
            Symbol connectedSymbol = connectedObj as Symbol;
2860
            Line targetLine = targetObj as Line;
2861
            Line connectedLine = connectedObj as Line;
2862
            if (targetSymbol != null && connectedSymbol != null)
2863
            {
2864
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2865
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2866

    
2867
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2868
                {
2869
                    if (connector.get_ItemStatus() != "Active")
2870
                        continue;
2871

    
2872
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2873
                    {
2874
                        targetConnector = connector;
2875
                        break;
2876
                    }
2877
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2878
                    {
2879
                        targetConnector = connector;
2880
                        break;
2881
                    }
2882
                }
2883

    
2884
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2885
                {
2886
                    if (connector.get_ItemStatus() != "Active")
2887
                        continue;
2888

    
2889
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2890
                    {
2891
                        targetConnector = connector;
2892
                        break;
2893
                    }
2894
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2895
                    {
2896
                        targetConnector = connector;
2897
                        break;
2898
                    }
2899
                }
2900

    
2901
                ReleaseCOMObjects(targetLMSymbol);
2902
                ReleaseCOMObjects(connectedLMSymbol);
2903
            }
2904
            else if (targetLine != null && connectedLine != null)
2905
            {
2906
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2907
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2908

    
2909
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2910
                {
2911
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2912
                    {
2913
                        if (targetConnector != null)
2914
                            break;
2915

    
2916
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2917
                        {
2918
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2919

    
2920
                            if (IsConnected(_LMConnector, connectedModelItem))
2921
                                targetConnector = _LMConnector;
2922
                            else
2923
                                ReleaseCOMObjects(_LMConnector);
2924
                        }
2925
                    }
2926

    
2927
                    ReleaseCOMObjects(targetModelItem);
2928
                }
2929
            }
2930
            else
2931
            {
2932
                LMSymbol connectedLMSymbol = null;
2933
                if (connectedSymbol != null)
2934
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2935
                else if (targetSymbol != null)
2936
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2937
                else
2938
                {
2939

    
2940
                }
2941
                LMModelItem targetModelItem = null;
2942
                if (targetLine != null)
2943
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2944
                else if (connectedLine != null)
2945
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2946
                else
2947
                {
2948

    
2949
                }
2950
                if (connectedLMSymbol != null && targetModelItem != null)
2951
                {
2952
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2953
                    {
2954
                        if (connector.get_ItemStatus() != "Active")
2955
                            continue;
2956

    
2957
                        if (IsConnected(connector, targetModelItem))
2958
                        {
2959
                            targetConnector = connector;
2960
                            break;
2961
                        }
2962
                    }
2963

    
2964
                    if (targetConnector == null)
2965
                    {
2966
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2967
                        {
2968
                            if (connector.get_ItemStatus() != "Active")
2969
                                continue;
2970

    
2971
                            if (IsConnected(connector, targetModelItem))
2972
                            {
2973
                                targetConnector = connector;
2974
                                break;
2975
                            }
2976
                        }
2977
                    }
2978
                }
2979

    
2980
            }
2981

    
2982
            return targetConnector;
2983
        }
2984

    
2985
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2986
        {
2987
            double[] result = null;
2988
            Line targetLine = targetObj as Line;
2989
            Symbol targetSymbol = targetObj as Symbol;
2990
            Line connLine = connObj as Line;
2991
            Symbol connSymbol = connObj as Symbol;
2992

    
2993
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
2994
            double lineMove = GridSetting.GetInstance().Length * 3;
2995
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2996
            {
2997
                result = GetConnectorVertices(targetConnector)[0];
2998
                if (targetSymbol != null && connSymbol != null)
2999
                {
3000
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3001
                    if (slopeType == SlopeType.HORIZONTAL)
3002
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3003
                    else if (slopeType == SlopeType.VERTICAL)
3004
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3005
                }
3006
                else if (targetLine != null)
3007
                {
3008
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3009
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3010
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3011
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3012
                }
3013
                else if (connLine != null)
3014
                {
3015
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3016
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3017
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3018
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3019
                }
3020
            }
3021
            else
3022
            {
3023
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3024
                {
3025
                    Line line = connObj as Line;
3026
                    LMConnector connectedConnector = null;
3027
                    int connIndex = 0;
3028
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3029
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3030

    
3031
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3032

    
3033
                    ReleaseCOMObjects(modelItem);
3034
                    ReleaseCOMObjects(connectedConnector);
3035

    
3036
                    if (vertices.Count > 0)
3037
                    {
3038
                        if (connIndex == 1)
3039
                            result = vertices[0];
3040
                        else if (connIndex == 2)
3041
                            result = vertices[vertices.Count - 1];
3042

    
3043
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3044
                        {
3045
                            result = new double[] { result[0], result[1] - lineMove };
3046
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3047
                            {
3048
                                result = new double[] { result[0] - lineMove, result[1] };
3049
                            }
3050
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3051
                            {
3052
                                result = new double[] { result[0] + lineMove, result[1] };
3053
                            }
3054
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3055
                            {
3056
                                result = new double[] { result[0] + lineMove, result[1] };
3057
                            }
3058
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3059
                            {
3060
                                result = new double[] { result[0] - lineMove, result[1] };
3061
                            }
3062
                        }
3063
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3064
                        {
3065
                            result = new double[] { result[0] - lineMove, result[1] };
3066
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3067
                            {
3068
                                result = new double[] { result[0], result[1] - lineMove };
3069
                            }
3070
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3071
                            {
3072
                                result = new double[] { result[0], result[1] + lineMove };
3073
                            }
3074
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3075
                            {
3076
                                result = new double[] { result[0], result[1] + lineMove };
3077
                            }
3078
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3079
                            {
3080
                                result = new double[] { result[0], result[1] - lineMove };
3081
                            }
3082
                        }
3083
                            
3084
                    }
3085
                }
3086
                else
3087
                {
3088
                    Log.Write("error in GetSegemtPoint");
3089
                }
3090
            }
3091

    
3092
            return result;
3093
        }
3094

    
3095
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3096
        {
3097
            bool result = false;
3098

    
3099
            foreach (LMRepresentation rep in modelItem.Representations)
3100
            {
3101
                if (result)
3102
                    break;
3103

    
3104
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3105
                {
3106
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3107

    
3108
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3109
                        connector.ConnectItem1SymbolObject != null &&
3110
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3111
                    {
3112
                        result = true;
3113
                        ReleaseCOMObjects(_LMConnector);
3114
                        break;
3115
                    }
3116
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3117
                        connector.ConnectItem2SymbolObject != null &&
3118
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3119
                    {
3120
                        result = true;
3121
                        ReleaseCOMObjects(_LMConnector);
3122
                        break;
3123
                    }
3124
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3125
                        connector.ConnectItem1SymbolObject != null &&
3126
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3127
                    {
3128
                        result = true;
3129
                        ReleaseCOMObjects(_LMConnector);
3130
                        break;
3131
                    }
3132
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3133
                        connector.ConnectItem2SymbolObject != null &&
3134
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3135
                    {
3136
                        result = true;
3137
                        ReleaseCOMObjects(_LMConnector);
3138
                        break;
3139
                    }
3140

    
3141
                    ReleaseCOMObjects(_LMConnector);
3142
                }
3143
            }
3144

    
3145

    
3146
            return result;
3147
        }
3148

    
3149
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3150
        {
3151
            foreach (LMRepresentation rep in modelItem.Representations)
3152
            {
3153
                if (connectedConnector != null)
3154
                    break;
3155

    
3156
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3157
                {
3158
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3159

    
3160
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3161
                        connector.ConnectItem1SymbolObject != null &&
3162
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3163
                    {
3164
                        connectedConnector = _LMConnector;
3165
                        connectorIndex = 1;
3166
                        break;
3167
                    }
3168
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3169
                        connector.ConnectItem2SymbolObject != null &&
3170
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3171
                    {
3172
                        connectedConnector = _LMConnector;
3173
                        connectorIndex = 2;
3174
                        break;
3175
                    }
3176
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3177
                        connector.ConnectItem1SymbolObject != null &&
3178
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3179
                    {
3180
                        connectedConnector = _LMConnector;
3181
                        connectorIndex = 1;
3182
                        break;
3183
                    }
3184
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3185
                        connector.ConnectItem2SymbolObject != null &&
3186
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3187
                    {
3188
                        connectedConnector = _LMConnector;
3189
                        connectorIndex = 2;
3190
                        break;
3191
                    }
3192

    
3193
                    if (connectedConnector == null)
3194
                        ReleaseCOMObjects(_LMConnector);
3195
                }
3196
            }
3197
        }
3198

    
3199
        /// <summary>
3200
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3201
        /// </summary>
3202
        /// <param name="modelItemID1"></param>
3203
        /// <param name="modelItemID2"></param>
3204
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
3205
        {
3206
            try
3207
            {
3208
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3209
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
3210
                List<double[]> vertices1 = null;
3211
                string graphicOID1 = string.Empty;
3212
                if (connector1 != null)
3213
                {
3214
                    vertices1 = GetConnectorVertices(connector1);
3215
                    graphicOID1 = connector1.get_GraphicOID();
3216
                }
3217
                _LMAItem item1 = modelItem1.AsLMAItem();
3218
                ReleaseCOMObjects(connector1);
3219
                connector1 = null;
3220

    
3221
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3222
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3223
                List<double[]> vertices2 = null;
3224
                string graphicOID2 = string.Empty;
3225
                if (connector2 != null)
3226
                {
3227
                    vertices2 = GetConnectorVertices(connector2);
3228
                    graphicOID2 = connector2.get_GraphicOID();
3229
                }
3230
                _LMAItem item2 = modelItem2.AsLMAItem();
3231
                ReleaseCOMObjects(connector2);
3232
                connector2 = null;
3233

    
3234
                // item2가 item1으로 조인
3235
                _placement.PIDJoinRuns(ref item1, ref item2);
3236
                item1.Commit();
3237
                item2.Commit();
3238

    
3239
                string beforeID = string.Empty;
3240
                string afterID = string.Empty;
3241

    
3242
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3243
                {
3244
                    beforeID = modelItem2.Id;
3245
                    afterID = modelItem1.Id;
3246
                    survivorId = afterID;
3247
                }
3248
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3249
                {
3250
                    beforeID = modelItem1.Id;
3251
                    afterID = modelItem2.Id;
3252
                    survivorId = afterID;
3253
                }
3254
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3255
                {
3256
                    int model1Cnt = GetConnectorCount(modelId1);
3257
                    int model2Cnt = GetConnectorCount(modelId2);
3258
                    if (model1Cnt == 0)
3259
                    {
3260
                        beforeID = modelItem1.Id;
3261
                        afterID = modelItem2.Id;
3262
                        survivorId = afterID;
3263
                    }
3264
                    else if (model2Cnt == 0)
3265
                    {
3266
                        beforeID = modelItem2.Id;
3267
                        afterID = modelItem1.Id;
3268
                        survivorId = afterID;
3269
                    }
3270
                    else
3271
                        survivorId = null;
3272
                }
3273
                else
3274
                {
3275
                    Log.Write("잘못된 경우");
3276
                    survivorId = null;
3277
                }
3278

    
3279
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3280
                {
3281
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3282
                    foreach (var line in lines)
3283
                        line.SPPID.ModelItemId = afterID;
3284
                }
3285

    
3286
                ReleaseCOMObjects(modelItem1);
3287
                ReleaseCOMObjects(item1);
3288
                ReleaseCOMObjects(modelItem2);
3289
                ReleaseCOMObjects(item2);
3290
            }
3291
            catch (Exception ex)
3292
            {
3293
                Log.Write("Join Error");
3294
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3295
            }
3296
        }
3297

    
3298
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3299
        {
3300
            List<string> temp = new List<string>();
3301
            List<LMConnector> connectors = new List<LMConnector>();
3302
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3303
            {
3304
                if (connector.get_ItemStatus() != "Active")
3305
                    continue;
3306

    
3307
                LMModelItem modelItem = connector.ModelItemObject;
3308
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3309
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3310
                    temp.Add(modelItem.Id);
3311

    
3312
                if (temp.Contains(modelItem.Id) &&
3313
                    connOtherSymbol != null &&
3314
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3315
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3316
                    temp.Remove(modelItem.Id);
3317

    
3318

    
3319
                if (temp.Contains(modelItem.Id))
3320
                    connectors.Add(connector);
3321
                ReleaseCOMObjects(connOtherSymbol);
3322
                connOtherSymbol = null;
3323
                ReleaseCOMObjects(modelItem);
3324
                modelItem = null;
3325
            }
3326

    
3327
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3328
            {
3329
                if (connector.get_ItemStatus() != "Active")
3330
                    continue;
3331

    
3332
                LMModelItem modelItem = connector.ModelItemObject;
3333
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3334
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3335
                    temp.Add(modelItem.Id);
3336

    
3337
                if (temp.Contains(modelItem.Id) &&
3338
                    connOtherSymbol != null &&
3339
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3340
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3341
                    temp.Remove(modelItem.Id);
3342

    
3343
                if (temp.Contains(modelItem.Id))
3344
                    connectors.Add(connector);
3345
                ReleaseCOMObjects(connOtherSymbol);
3346
                connOtherSymbol = null;
3347
                ReleaseCOMObjects(modelItem);
3348
                modelItem = null;
3349
            }
3350

    
3351

    
3352
            List<string> result = new List<string>();
3353
            string originalName = GetSPPIDFileName(modelId);
3354
            foreach (var connector in connectors)
3355
            {
3356
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3357
                if (originalName == fileName)
3358
                    result.Add(connector.ModelItemID);
3359
                else
3360
                {
3361
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3362
                        result.Add(connector.ModelItemID);
3363
                    else
3364
                    {
3365
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3366
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3367
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3368
                            result.Add(connector.ModelItemID);
3369
                    }
3370
                }
3371
            }
3372

    
3373
            foreach (var connector in connectors)
3374
                ReleaseCOMObjects(connector);
3375
            
3376
            return result;
3377

    
3378

    
3379
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3380
            {
3381
                LMSymbol findResult = null;
3382
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3383
                    findResult = connector.ConnectItem1SymbolObject;
3384
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3385
                    findResult = connector.ConnectItem2SymbolObject;
3386

    
3387
                return findResult;
3388
            }
3389
        }
3390

    
3391
        /// <summary>
3392
        /// PipeRun의 좌표를 가져오는 메서드
3393
        /// </summary>
3394
        /// <param name="modelId"></param>
3395
        /// <returns></returns>
3396
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3397
        {
3398
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3399
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3400

    
3401
            if (modelItem != null)
3402
            {
3403
                foreach (LMRepresentation rep in modelItem.Representations)
3404
                {
3405
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3406
                    {
3407
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3408
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3409
                        {
3410
                            ReleaseCOMObjects(_LMConnector);
3411
                            _LMConnector = null;
3412
                            continue;
3413
                        }
3414
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3415
                        dynamic OID = rep.get_GraphicOID().ToString();
3416
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3417
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3418
                        int verticesCount = lineStringGeometry.VertexCount;
3419
                        double[] vertices = null;
3420
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3421
                        for (int i = 0; i < verticesCount; i++)
3422
                        {
3423
                            double x = 0;
3424
                            double y = 0;
3425
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3426
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3427
                        }
3428
                    }
3429
                }
3430

    
3431
                ReleaseCOMObjects(modelItem);
3432
            }
3433

    
3434
            return connectorVertices;
3435
        }
3436

    
3437
        private List<double[]> GetConnectorVertices(LMConnector connector)
3438
        {
3439
            List<double[]> vertices = new List<double[]>();
3440
            if (connector != null)
3441
            {
3442
                dynamic OID = connector.get_GraphicOID().ToString();
3443
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3444
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3445
                int verticesCount = lineStringGeometry.VertexCount;
3446
                double[] value = null;
3447
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3448
                for (int i = 0; i < verticesCount; i++)
3449
                {
3450
                    double x = 0;
3451
                    double y = 0;
3452
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3453
                    vertices.Add(new double[] { x, y });
3454
                }
3455
            }
3456
            return vertices;
3457
        }
3458

    
3459
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
3460
        {
3461
            List<double[]> vertices = null;
3462
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
3463
            if (drawingObject != null)
3464
            {
3465
                vertices = new List<double[]>();
3466
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3467
                int verticesCount = lineStringGeometry.VertexCount;
3468
                double[] value = null;
3469
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3470
                for (int i = 0; i < verticesCount; i++)
3471
                {
3472
                    double x = 0;
3473
                    double y = 0;
3474
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3475
                    vertices.Add(new double[] { x, y });
3476
                }
3477
            }
3478
            return vertices;
3479
        }
3480
        /// <summary>
3481
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3482
        /// </summary>
3483
        /// <param name="connectorVertices"></param>
3484
        /// <param name="connX"></param>
3485
        /// <param name="connY"></param>
3486
        /// <returns></returns>
3487
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3488
        {
3489
            double length = double.MaxValue;
3490
            LMConnector targetConnector = null;
3491
            foreach (var item in connectorVertices)
3492
            {
3493
                List<double[]> points = item.Value;
3494
                for (int i = 0; i < points.Count - 1; i++)
3495
                {
3496
                    double[] point1 = points[i];
3497
                    double[] point2 = points[i + 1];
3498
                    double x1 = Math.Min(point1[0], point2[0]);
3499
                    double y1 = Math.Min(point1[1], point2[1]);
3500
                    double x2 = Math.Max(point1[0], point2[0]);
3501
                    double y2 = Math.Max(point1[1], point2[1]);
3502

    
3503
                    if ((x1 <= connX && x2 >= connX) ||
3504
                        (y1 <= connY && y2 >= connY))
3505
                    {
3506
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3507
                        if (length >= distance)
3508
                        {
3509
                            targetConnector = item.Key;
3510
                            length = distance;
3511
                        }
3512

    
3513
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3514
                        if (length >= distance)
3515
                        {
3516
                            targetConnector = item.Key;
3517
                            length = distance;
3518
                        }
3519
                    }
3520
                }
3521
            }
3522

    
3523
            // 못찾았을때.
3524
            length = double.MaxValue;
3525
            if (targetConnector == null)
3526
            {
3527
                foreach (var item in connectorVertices)
3528
                {
3529
                    List<double[]> points = item.Value;
3530

    
3531
                    foreach (double[] point in points)
3532
                    {
3533
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3534
                        if (length >= distance)
3535
                        {
3536
                            targetConnector = item.Key;
3537
                            length = distance;
3538
                        }
3539
                    }
3540
                }
3541
            }
3542

    
3543
            return targetConnector;
3544
        }
3545

    
3546
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3547
        {
3548
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3549
            if (vertices.Count == 0)
3550
                return null;
3551

    
3552
            double length = double.MaxValue;
3553
            LMConnector targetConnector = null;
3554
            double[] resultPoint = null;
3555
            List<double[]> targetVertices = null;
3556

    
3557
            // Vertices 포인트에 제일 가까운곳
3558
            foreach (var item in vertices)
3559
            {
3560
                List<double[]> points = item.Value;
3561
                for (int i = 0; i < points.Count; i++)
3562
                {
3563
                    double[] point = points[i];
3564
                    double tempX = point[0];
3565
                    double tempY = point[1];
3566

    
3567
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3568
                    if (length >= distance)
3569
                    {
3570
                        targetConnector = item.Key;
3571
                        length = distance;
3572
                        resultPoint = point;
3573
                        targetVertices = item.Value;
3574
                    }
3575
                }
3576
            }
3577

    
3578
            // Vertices Cross에 제일 가까운곳
3579
            foreach (var item in vertices)
3580
            {
3581
                List<double[]> points = item.Value;
3582
                for (int i = 0; i < points.Count - 1; i++)
3583
                {
3584
                    double[] point1 = points[i];
3585
                    double[] point2 = points[i + 1];
3586

    
3587
                    double maxLineX = Math.Max(point1[0], point2[0]);
3588
                    double minLineX = Math.Min(point1[0], point2[0]);
3589
                    double maxLineY = Math.Max(point1[1], point2[1]);
3590
                    double minLineY = Math.Min(point1[1], point2[1]);
3591

    
3592
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3593

    
3594
                    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]);
3595
                    if (crossingPoint != null)
3596
                    {
3597
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3598
                        if (length >= distance)
3599
                        {
3600
                            if (slope == SlopeType.Slope &&
3601
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3602
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3603
                            {
3604
                                targetConnector = item.Key;
3605
                                length = distance;
3606
                                resultPoint = crossingPoint;
3607
                                targetVertices = item.Value;
3608
                            }
3609
                            else if (slope == SlopeType.HORIZONTAL &&
3610
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3611
                            {
3612
                                targetConnector = item.Key;
3613
                                length = distance;
3614
                                resultPoint = crossingPoint;
3615
                                targetVertices = item.Value;
3616
                            }
3617
                            else if (slope == SlopeType.VERTICAL &&
3618
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3619
                            {
3620
                                targetConnector = item.Key;
3621
                                length = distance;
3622
                                resultPoint = crossingPoint;
3623
                                targetVertices = item.Value;
3624
                            }
3625
                        }
3626
                    }
3627
                }
3628
            }
3629

    
3630
            foreach (var item in vertices)
3631
                if (item.Key != null && item.Key != targetConnector)
3632
                    ReleaseCOMObjects(item.Key);
3633

    
3634
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3635
            {
3636
                double tempResultX = resultPoint[0];
3637
                double tempResultY = resultPoint[1];
3638
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3639

    
3640
                GridSetting gridSetting = GridSetting.GetInstance();
3641

    
3642
                for (int i = 0; i < targetVertices.Count; i++)
3643
                {
3644
                    double[] point = targetVertices[i];
3645
                    double tempX = targetVertices[i][0];
3646
                    double tempY = targetVertices[i][1];
3647
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3648
                    if (tempX == tempResultX && tempY == tempResultY)
3649
                    {
3650
                        if (i == 0)
3651
                        {
3652
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3653
                            bool containZeroLength = false;
3654
                            if (connSymbol != null)
3655
                            {
3656
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3657
                                {
3658
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3659
                                        containZeroLength = true;
3660
                                }
3661
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3662
                                {
3663
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3664
                                        containZeroLength = true;
3665
                                }
3666
                            }
3667

    
3668
                            if (connSymbol == null ||
3669
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3670
                                containZeroLength)
3671
                            {
3672
                                bool bCalcX = false;
3673
                                bool bCalcY = false;
3674
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3675
                                    bCalcX = true;
3676
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3677
                                    bCalcY = true;
3678
                                else
3679
                                {
3680
                                    bCalcX = true;
3681
                                    bCalcY = true;
3682
                                }
3683

    
3684
                                if (bCalcX)
3685
                                {
3686
                                    double nextX = targetVertices[i + 1][0];
3687
                                    double newX = 0;
3688
                                    if (nextX > tempX)
3689
                                    {
3690
                                        newX = tempX + gridSetting.Length;
3691
                                        if (newX > nextX)
3692
                                            newX = (point[0] + nextX) / 2;
3693
                                    }
3694
                                    else
3695
                                    {
3696
                                        newX = tempX - gridSetting.Length;
3697
                                        if (newX < nextX)
3698
                                            newX = (point[0] + nextX) / 2;
3699
                                    }
3700
                                    resultPoint = new double[] { newX, resultPoint[1] };
3701
                                }
3702

    
3703
                                if (bCalcY)
3704
                                {
3705
                                    double nextY = targetVertices[i + 1][1];
3706
                                    double newY = 0;
3707
                                    if (nextY > tempY)
3708
                                    {
3709
                                        newY = tempY + gridSetting.Length;
3710
                                        if (newY > nextY)
3711
                                            newY = (point[1] + nextY) / 2;
3712
                                    }
3713
                                    else
3714
                                    {
3715
                                        newY = tempY - gridSetting.Length;
3716
                                        if (newY < nextY)
3717
                                            newY = (point[1] + nextY) / 2;
3718
                                    }
3719
                                    resultPoint = new double[] { resultPoint[0], newY };
3720
                                }
3721
                            }
3722
                        }
3723
                        else if (i == targetVertices.Count - 1)
3724
                        {
3725
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3726
                            bool containZeroLength = false;
3727
                            if (connSymbol != null)
3728
                            {
3729
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3730
                                {
3731
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3732
                                        containZeroLength = true;
3733
                                }
3734
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3735
                                {
3736
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3737
                                        containZeroLength = true;
3738
                                }
3739
                            }
3740

    
3741
                            if (connSymbol == null ||
3742
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3743
                                containZeroLength)
3744
                            {
3745
                                bool bCalcX = false;
3746
                                bool bCalcY = false;
3747
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3748
                                    bCalcX = true;
3749
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3750
                                    bCalcY = true;
3751
                                else
3752
                                {
3753
                                    bCalcX = true;
3754
                                    bCalcY = true;
3755
                                }
3756

    
3757
                                if (bCalcX)
3758
                                {
3759
                                    double nextX = targetVertices[i - 1][0];
3760
                                    double newX = 0;
3761
                                    if (nextX > tempX)
3762
                                    {
3763
                                        newX = tempX + gridSetting.Length;
3764
                                        if (newX > nextX)
3765
                                            newX = (point[0] + nextX) / 2;
3766
                                    }
3767
                                    else
3768
                                    {
3769
                                        newX = tempX - gridSetting.Length;
3770
                                        if (newX < nextX)
3771
                                            newX = (point[0] + nextX) / 2;
3772
                                    }
3773
                                    resultPoint = new double[] { newX, resultPoint[1] };
3774
                                }
3775

    
3776
                                if (bCalcY)
3777
                                {
3778
                                    double nextY = targetVertices[i - 1][1];
3779
                                    double newY = 0;
3780
                                    if (nextY > tempY)
3781
                                    {
3782
                                        newY = tempY + gridSetting.Length;
3783
                                        if (newY > nextY)
3784
                                            newY = (point[1] + nextY) / 2;
3785
                                    }
3786
                                    else
3787
                                    {
3788
                                        newY = tempY - gridSetting.Length;
3789
                                        if (newY < nextY)
3790
                                            newY = (point[1] + nextY) / 2;
3791
                                    }
3792
                                    resultPoint = new double[] { resultPoint[0], newY };
3793
                                }
3794
                            }
3795
                        }
3796
                        break;
3797
                    }
3798
                }
3799
            }
3800

    
3801
            x = resultPoint[0];
3802
            y = resultPoint[1];
3803

    
3804
            return targetConnector;
3805
        }
3806

    
3807
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3808
        {
3809
            LMConnector result = null;
3810
            List<LMConnector> connectors = new List<LMConnector>();
3811
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3812

    
3813
            if (modelItem != null)
3814
            {
3815
                foreach (LMRepresentation rep in modelItem.Representations)
3816
                {
3817
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3818
                        connectors.Add(dataSource.GetConnector(rep.Id));
3819
                }
3820

    
3821
                ReleaseCOMObjects(modelItem);
3822
            }
3823

    
3824
            if (connectors.Count == 1)
3825
                result = connectors[0];
3826
            else
3827
                foreach (var item in connectors)
3828
                    ReleaseCOMObjects(item);
3829

    
3830
            return result;
3831
        }
3832

    
3833
        private LMConnector GetLMConnectorFirst(string modelItemID)
3834
        {
3835
            LMConnector result = null;
3836
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3837

    
3838
            if (modelItem != null)
3839
            {
3840
                foreach (LMRepresentation rep in modelItem.Representations)
3841
                {
3842
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
3843
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
3844
                    {
3845
                        LMConnector connector = dataSource.GetConnector(rep.Id);
3846
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
3847
                        {
3848
                            result = connector;
3849
                            break;
3850
                        }
3851
                        else
3852
                        {
3853
                            ReleaseCOMObjects(connector);
3854
                            connector = null;
3855
                        }
3856
                    }
3857
                }
3858
                ReleaseCOMObjects(modelItem);
3859
                modelItem = null;
3860
            }
3861

    
3862
            return result;
3863
        }
3864

    
3865
        private int GetConnectorCount(string modelItemID)
3866
        {
3867
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3868
            int result = 0;
3869
            if (modelItem != null)
3870
            {
3871
                foreach (LMRepresentation rep in modelItem.Representations)
3872
                {
3873
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3874
                        result++;
3875
                    ReleaseCOMObjects(rep);
3876
                }
3877
                ReleaseCOMObjects(modelItem);
3878
            }
3879

    
3880
            return result;
3881
        }
3882

    
3883
        public List<string> GetRepresentations(string modelItemID)
3884
        {
3885
            List<string> result = new List<string>(); ;
3886
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3887
            if (modelItem != null)
3888
            {
3889
                foreach (LMRepresentation rep in modelItem.Representations)
3890
                {
3891
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3892
                        result.Add(rep.Id);
3893
                }
3894
                ReleaseCOMObjects(modelItem);
3895
            }
3896

    
3897
            return result;
3898
        }
3899

    
3900
        /// <summary>
3901
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3902
        /// </summary>
3903
        /// <param name="lineNumber"></param>
3904
        private void LineNumberModelingOnlyOne(Line line)
3905
        {
3906
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3907
            if (lineNumber != null)
3908
            {
3909
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3910
                if (connectedLMConnector != null)
3911
                {
3912
                    double x = 0;
3913
                    double y = 0;
3914
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3915

    
3916
                    Array points = new double[] { 0, x, y };
3917
                    lineNumber.SPPID.SPPID_X = x;
3918
                    lineNumber.SPPID.SPPID_Y = y;
3919
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3920

    
3921
                    if (_LmLabelPresist != null)
3922
                    {
3923
                        _LmLabelPresist.Commit();
3924
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3925
                        ReleaseCOMObjects(_LmLabelPresist);
3926
                    }
3927
                }
3928
            }
3929
        }
3930

    
3931
        private void LineNumberModeling(LineNumber lineNumber)
3932
        {
3933
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3934
            if (line != null)
3935
            {
3936
                double x = 0;
3937
                double y = 0;
3938
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3939

    
3940
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3941
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3942
                if (connectedLMConnector != null)
3943
                {
3944
                    Array points = new double[] { 0, x, y };
3945
                    lineNumber.SPPID.SPPID_X = x;
3946
                    lineNumber.SPPID.SPPID_Y = y;
3947
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3948

    
3949
                    if (_LmLabelPresist != null)
3950
                    {
3951
                        _LmLabelPresist.Commit();
3952
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3953
                        ReleaseCOMObjects(_LmLabelPresist);
3954
                    }
3955
                }
3956

    
3957
                foreach (var item in connectorVertices)
3958
                    ReleaseCOMObjects(item.Key);
3959
            }
3960
        }
3961
        private void LineNumberCorrectModeling(LineNumber lineNumber)
3962
        {
3963
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3964
            if (line == null || line.SPPID.Vertices == null)
3965
                return;
3966

    
3967
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
3968
            {
3969
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
3970
                if (removeLabel != null)
3971
                {
3972
                    GridSetting gridSetting = GridSetting.GetInstance();
3973
                    double[] labelRange = null;
3974
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
3975
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
3976
                    List<double[]> vertices = GetConnectorVertices(connector);
3977

    
3978
                    double[] resultStart = null;
3979
                    double[] resultEnd = null;
3980
                    double distance = double.MaxValue;
3981
                    for (int i = 0; i < vertices.Count - 1; i++)
3982
                    {
3983
                        double[] startPoint = vertices[i];
3984
                        double[] endPoint = vertices[i + 1];
3985
                        foreach (var item in line.SPPID.Vertices)
3986
                        {
3987
                            double[] lineStartPoint = item[0];
3988
                            double[] lineEndPoint = item[item.Count - 1];
3989

    
3990
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
3991
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
3992
                            if (tempDistance < distance)
3993
                            {
3994
                                distance = tempDistance;
3995
                                resultStart = startPoint;
3996
                                resultEnd = endPoint;
3997
                            }
3998
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
3999
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4000
                            if (tempDistance < distance)
4001
                            {
4002
                                distance = tempDistance;
4003
                                resultStart = startPoint;
4004
                                resultEnd = endPoint;
4005
                            }
4006
                        }
4007
                    }
4008

    
4009
                    if (resultStart != null && resultEnd != null)
4010
                    {
4011
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4012
                        double lineStartX = 0;
4013
                        double lineStartY = 0;
4014
                        double lineEndX = 0;
4015
                        double lineEndY = 0;
4016
                        double lineNumberX = 0;
4017
                        double lineNumberY = 0;
4018
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4019
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4020

    
4021
                        double lineX = (lineStartX + lineEndX) / 2;
4022
                        double lineY = (lineStartY + lineEndY) / 2;
4023
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4024
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4025

    
4026
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4027
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4028
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4029
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4030

    
4031
                        double offsetX = 0;
4032
                        double offsetY = 0;
4033
                        if (slope == SlopeType.HORIZONTAL)
4034
                        {
4035
                            // Line Number 아래
4036
                            if (lineY < lineNumberY)
4037
                            {
4038
                                offsetX = labelCenterX - SPPIDCenterX;
4039
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4040
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4041
                            }
4042
                            // Line Number 위
4043
                            else
4044
                            {
4045
                                offsetX = labelCenterX - SPPIDCenterX;
4046
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4047
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4048
                            }
4049
                        }
4050
                        else if (slope == SlopeType.VERTICAL)
4051
                        {
4052
                            // Line Number 오르쪽
4053
                            if (lineX < lineNumberX)
4054
                            {
4055
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4056
                                offsetY = labelCenterY - SPPIDCenterY;
4057
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4058
                            }
4059
                            // Line Number 왼쪽
4060
                            else
4061
                            {
4062
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4063
                                offsetY = labelCenterY - SPPIDCenterY;
4064
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4065
                            }
4066
                        }
4067

    
4068
                        if (offsetY != 0 && offsetY != 0)
4069
                        {
4070
                            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4071
                            Array points = new double[] { 0, lineNumber.SPPID.SPPID_X, lineNumber.SPPID.SPPID_Y };
4072
                            LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connector.AsLMRepresentation(), IsLeaderVisible: false);
4073

    
4074
                            if (_LmLabelPresist != null)
4075
                            {
4076
                                _LmLabelPresist.Commit();
4077
                                lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4078
                            }
4079
                            ReleaseCOMObjects(_LmLabelPresist);
4080
                            _LmLabelPresist = null; 
4081
                        }
4082

    
4083
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4084
                        {
4085
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4086
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4087
                        }
4088
                    }
4089

    
4090

    
4091
                    ReleaseCOMObjects(connector);
4092
                    connector = null;
4093
                }
4094

    
4095
                ReleaseCOMObjects(removeLabel);
4096
                removeLabel = null;
4097
            }
4098
        }
4099
        /// <summary>
4100
        /// Flow Mark Modeling
4101
        /// </summary>
4102
        /// <param name="line"></param>
4103
        private void FlowMarkModeling(Line line)
4104
        {
4105
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4106
            {
4107
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4108
                if (connector != null)
4109
                {
4110
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4111
                    List<double[]> vertices = GetConnectorVertices(connector);
4112
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4113
                    double[] point = vertices[vertices.Count - 1];
4114
                    Array array = new double[] { 0, point[0], point[1] };
4115
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4116
                    if (_LMLabelPersist != null)
4117
                    {
4118
                        _LMLabelPersist.Commit();
4119
                        ReleaseCOMObjects(_LMLabelPersist);
4120
                    }
4121
                        
4122
                }
4123
            }
4124
        }
4125

    
4126
        /// <summary>
4127
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4128
        /// </summary>
4129
        /// <param name="lineNumber"></param>
4130
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4131
        {
4132
            foreach (LineRun run in lineNumber.RUNS)
4133
            {
4134
                foreach (var item in run.RUNITEMS)
4135
                {
4136
                    if (item.GetType() == typeof(Symbol))
4137
                    {
4138
                        Symbol symbol = item as Symbol;
4139
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4140
                        if (_LMSymbol != null)
4141
                        {
4142
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4143

    
4144
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4145
                            {
4146
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4147
                                {
4148
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4149
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4150
                                    {
4151
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4152
                                        if (_LMAAttribute != null)
4153
                                        {
4154
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4155
                                                _LMAAttribute.set_Value(attribute.VALUE);
4156
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4157
                                                _LMAAttribute.set_Value(attribute.VALUE);
4158
                                        }
4159
                                    }
4160
                                }
4161
                                _LMModelItem.Commit();
4162
                            }
4163
                            if (_LMModelItem != null)
4164
                                ReleaseCOMObjects(_LMModelItem);
4165
                        }
4166
                        if (_LMSymbol != null)
4167
                            ReleaseCOMObjects(_LMSymbol);
4168
                    }
4169
                    else if (item.GetType() == typeof(Line))
4170
                    {
4171
                        Line line = item as Line;
4172
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4173
                        {
4174
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4175
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4176
                            {
4177
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4178
                                {
4179
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4180
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4181
                                    {
4182
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4183
                                        if (_LMAAttribute != null)
4184
                                        {
4185
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4186
                                                _LMAAttribute.set_Value(attribute.VALUE);
4187
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4188
                                                _LMAAttribute.set_Value(attribute.VALUE);
4189

    
4190
                                        }
4191
                                    }
4192
                                }
4193
                                _LMModelItem.Commit();
4194
                            }
4195
                            if (_LMModelItem != null)
4196
                                ReleaseCOMObjects(_LMModelItem);
4197
                            endLine.Add(line.SPPID.ModelItemId);
4198
                        }
4199
                    }
4200
                }
4201
            }
4202
        }
4203

    
4204
        /// <summary>
4205
        /// Symbol Attribute 입력 메서드
4206
        /// </summary>
4207
        /// <param name="item"></param>
4208
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4209
        {
4210
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4211
            string sRep = null;
4212
            if (targetItem.GetType() == typeof(Symbol))
4213
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4214
            else if (targetItem.GetType() == typeof(Equipment))
4215
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4216

    
4217
            if (!string.IsNullOrEmpty(sRep))
4218
            {
4219
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4220
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4221
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4222
                
4223
                foreach (var item in targetAttributes)
4224
                {
4225
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4226
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4227
                    {
4228
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4229
                        if (_Attribute != null)
4230
                        {
4231
                            //object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
4232
                            //if (associItem != null)
4233
                            //{
4234
                            //    if (associItem.GetType() == typeof(Text))
4235
                            //    {
4236
                            //        Text text = associItem as Text;
4237
                            //        text.SPPID.RepresentationId = "Attribute";
4238
                            //    }
4239
                            //    else if (associItem.GetType() == typeof(Note))
4240
                            //    {
4241
                            //        Note note = associItem as Note;
4242
                            //        note.SPPID.RepresentationId = "Attribute";
4243
                            //    }
4244
                            //}
4245
                            _Attribute.set_Value(item.VALUE);
4246
                            // OPC 일경우 Attribute 저장
4247
                            if (targetItem.GetType() == typeof(Symbol))
4248
                            {
4249
                                Symbol symbol = targetItem as Symbol;
4250
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4251
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4252
                            }
4253
                        }
4254
                    }
4255
                }
4256
                _LMModelItem.Commit();
4257

    
4258
                ReleaseCOMObjects(_Attributes);
4259
                ReleaseCOMObjects(_LMModelItem);
4260
                ReleaseCOMObjects(_LMSymbol);
4261
            }
4262
        }
4263

    
4264
        /// <summary>
4265
        /// Input SpecBreak Attribute
4266
        /// </summary>
4267
        /// <param name="specBreak"></param>
4268
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4269
        {
4270
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4271
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4272

    
4273
            if (upStreamObj != null &&
4274
                downStreamObj != null)
4275
            {
4276
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4277

    
4278
                if (targetLMConnector != null)
4279
                {
4280
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4281
                    {
4282
                        string symbolPath = _LMLabelPersist.get_FileName();
4283
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4284
                        if (mapping != null)
4285
                        {
4286
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4287
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4288
                            {
4289
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4290
                                if (values.Length == 2)
4291
                                {
4292
                                    string upStreamValue = values[0];
4293
                                    string downStreamValue = values[1];
4294

    
4295
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4296
                                }
4297
                            }
4298
                        }
4299
                    }
4300

    
4301
                    ReleaseCOMObjects(targetLMConnector);
4302
                }
4303
            }
4304

    
4305

    
4306
            #region 내부에서만 쓰는 메서드
4307
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4308
            {
4309
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4310
                Line upStreamLine = _upStreamObj as Line;
4311
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4312
                Line downStreamLine = _downStreamObj as Line;
4313
                // 둘다 Line일 경우
4314
                if (upStreamLine != null && downStreamLine != null)
4315
                {
4316
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4317
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4318
                }
4319
                // 둘다 Symbol일 경우
4320
                else if (upStreamSymbol != null && downStreamSymbol != null)
4321
                {
4322
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4323
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4324
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4325

    
4326
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4327
                    {
4328
                        if (connector.get_ItemStatus() != "Active")
4329
                            continue;
4330

    
4331
                        if (connector.Id != zeroLenthConnector.Id)
4332
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4333
                    }
4334

    
4335
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4336
                    {
4337
                        if (connector.get_ItemStatus() != "Active")
4338
                            continue;
4339

    
4340
                        if (connector.Id != zeroLenthConnector.Id)
4341
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4342
                    }
4343

    
4344
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4345
                    {
4346
                        if (connector.get_ItemStatus() != "Active")
4347
                            continue;
4348

    
4349
                        if (connector.Id != zeroLenthConnector.Id)
4350
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4351
                    }
4352

    
4353
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4354
                    {
4355
                        if (connector.get_ItemStatus() != "Active")
4356
                            continue;
4357

    
4358
                        if (connector.Id != zeroLenthConnector.Id)
4359
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4360
                    }
4361

    
4362
                    ReleaseCOMObjects(zeroLenthConnector);
4363
                    ReleaseCOMObjects(upStreamLMSymbol);
4364
                    ReleaseCOMObjects(downStreamLMSymbol);
4365
                }
4366
                else if (upStreamSymbol != null && downStreamLine != null)
4367
                {
4368
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4369
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4370
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4371

    
4372
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4373
                    {
4374
                        if (connector.get_ItemStatus() != "Active")
4375
                            continue;
4376

    
4377
                        if (connector.Id == zeroLenthConnector.Id)
4378
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4379
                    }
4380

    
4381
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4382
                    {
4383
                        if (connector.get_ItemStatus() != "Active")
4384
                            continue;
4385

    
4386
                        if (connector.Id == zeroLenthConnector.Id)
4387
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4388
                    }
4389

    
4390
                    ReleaseCOMObjects(zeroLenthConnector);
4391
                    ReleaseCOMObjects(upStreamLMSymbol);
4392
                }
4393
                else if (upStreamLine != null && downStreamSymbol != null)
4394
                {
4395
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4396
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4397
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4398

    
4399
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4400
                    {
4401
                        if (connector.get_ItemStatus() != "Active")
4402
                            continue;
4403

    
4404
                        if (connector.Id == zeroLenthConnector.Id)
4405
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4406
                    }
4407

    
4408
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4409
                    {
4410
                        if (connector.get_ItemStatus() != "Active")
4411
                            continue;
4412

    
4413
                        if (connector.Id == zeroLenthConnector.Id)
4414
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4415
                    }
4416

    
4417
                    ReleaseCOMObjects(zeroLenthConnector);
4418
                    ReleaseCOMObjects(downStreamLMSymbol);
4419
                }
4420
            }
4421

    
4422
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4423
            {
4424
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4425
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4426
                {
4427
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4428
                    if (_LMAAttribute != null)
4429
                    {
4430
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4431
                            _LMAAttribute.set_Value(value);
4432
                        else if (_LMAAttribute.get_Value() != value)
4433
                            _LMAAttribute.set_Value(value);
4434
                    }
4435

    
4436
                    _LMModelItem.Commit();
4437
                }
4438
                if (_LMModelItem != null)
4439
                    ReleaseCOMObjects(_LMModelItem);
4440
            }
4441

    
4442
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4443
            {
4444
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4445
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4446
                {
4447
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4448
                    if (_LMAAttribute != null)
4449
                    {
4450
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4451
                            _LMAAttribute.set_Value(value);
4452
                        else if (_LMAAttribute.get_Value() != value)
4453
                            _LMAAttribute.set_Value(value);
4454
                    }
4455

    
4456
                    _LMModelItem.Commit();
4457
                }
4458
                if (_LMModelItem != null)
4459
                    ReleaseCOMObjects(_LMModelItem);
4460
            }
4461
            #endregion
4462
        }
4463

    
4464
        private void InputEndBreakAttribute(EndBreak endBreak)
4465
        {
4466
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4467
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4468

    
4469
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4470
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4471
            {
4472
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4473
                if (labelPersist != null)
4474
                {
4475
                    LMRepresentation representation = labelPersist.RepresentationObject;
4476
                    if (representation != null)
4477
                    {
4478
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4479
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4480
                        string modelItemID = connector.ModelItemID;
4481
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4482
                        {
4483
                            List<string> modelItemIDs = new List<string>();
4484
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4485
                            {
4486
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4487
                                foreach (LMConnector item in symbol.Connect1Connectors)
4488
                                {
4489
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4490
                                        modelItemIDs.Add(item.ModelItemID);
4491
                                    ReleaseCOMObjects(item);
4492
                                }
4493
                                foreach (LMConnector item in symbol.Connect2Connectors)
4494
                                {
4495
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4496
                                        modelItemIDs.Add(item.ModelItemID);
4497
                                    ReleaseCOMObjects(item);
4498
                                }
4499
                                ReleaseCOMObjects(symbol);
4500
                                symbol = null;
4501
                            }
4502
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4503
                            {
4504
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4505
                                foreach (LMConnector item in symbol.Connect1Connectors)
4506
                                {
4507
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4508
                                        modelItemIDs.Add(item.ModelItemID);
4509
                                    ReleaseCOMObjects(item);
4510
                                }
4511
                                foreach (LMConnector item in symbol.Connect2Connectors)
4512
                                {
4513
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4514
                                        modelItemIDs.Add(item.ModelItemID);
4515
                                    ReleaseCOMObjects(item);
4516
                                }
4517
                                ReleaseCOMObjects(symbol);
4518
                                symbol = null;
4519
                            }
4520

    
4521
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4522
                            if (modelItemIDs.Count == 1)
4523
                            {
4524
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4525
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4526
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4527
                                {
4528
                                    bool result = false;
4529
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4530
                                    {
4531
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4532
                                            result = true;
4533
                                        ReleaseCOMObjects(loop);
4534
                                    }
4535

    
4536
                                    if (result)
4537
                                    {
4538
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4539
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4540
                                        ZeroLengthModelItem.Commit();
4541
                                    }
4542
                                    else
4543
                                    {
4544
                                        List<string> loopModelItems = new List<string>();
4545
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
4546
                                        {
4547
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
4548
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4549
                                            {
4550
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4551
                                                    loopModelItems.Add(loop.ModelItemID);
4552
                                                ReleaseCOMObjects(loop);
4553
                                            }
4554
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4555
                                            {
4556
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4557
                                                    loopModelItems.Add(loop.ModelItemID);
4558
                                                ReleaseCOMObjects(loop);
4559
                                            }
4560
                                            ReleaseCOMObjects(_symbol);
4561
                                            _symbol = null;
4562
                                        }
4563
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
4564
                                        {
4565
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
4566
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4567
                                            {
4568
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4569
                                                    loopModelItems.Add(loop.ModelItemID);
4570
                                                ReleaseCOMObjects(loop);
4571
                                            }
4572
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4573
                                            {
4574
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4575
                                                    loopModelItems.Add(loop.ModelItemID);
4576
                                                ReleaseCOMObjects(loop);
4577
                                            }
4578
                                            ReleaseCOMObjects(_symbol);
4579
                                            _symbol = null;
4580
                                        }
4581

    
4582
                                        loopModelItems = loopModelItems.Distinct().ToList();
4583
                                        if (loopModelItems.Count == 1)
4584
                                        {
4585
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
4586
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
4587
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
4588
                                            modelItem.Commit();
4589
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4590
                                            ZeroLengthModelItem.Commit();
4591

    
4592
                                            ReleaseCOMObjects(loopModelItem);
4593
                                            loopModelItem = null;
4594
                                        }
4595
                                    }
4596
                                }
4597
                                else
4598
                                {
4599
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4600
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4601
                                    ZeroLengthModelItem.Commit();
4602
                                }
4603
                                ReleaseCOMObjects(modelItem);
4604
                                modelItem = null;
4605
                                ReleaseCOMObjects(onlyOne);
4606
                                onlyOne = null;
4607
                            }
4608
                        }
4609
                        ReleaseCOMObjects(connector);
4610
                        connector = null;
4611
                        ReleaseCOMObjects(ZeroLengthModelItem);
4612
                        ZeroLengthModelItem = null;
4613
                    }
4614
                    ReleaseCOMObjects(representation);
4615
                    representation = null;
4616
                }
4617
                ReleaseCOMObjects(labelPersist);
4618
                labelPersist = null;
4619
            }
4620
        }
4621

    
4622
        /// <summary>
4623
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
4624
        /// </summary>
4625
        /// <param name="text"></param>
4626
        private void NormalTextModeling(Text text)
4627
        {
4628
            LMSymbol _LMSymbol = null;
4629

    
4630
            LMItemNote _LMItemNote = null;
4631
            LMAAttribute _LMAAttribute = null;
4632

    
4633
            double x = 0;
4634
            double y = 0;
4635
            double angle = text.ANGLE;
4636
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
4637

    
4638
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4639
            text.SPPID.SPPID_X = x;
4640
            text.SPPID.SPPID_Y = y;
4641

    
4642
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
4643
            if (_LMSymbol != null)
4644
            {
4645
                _LMSymbol.Commit();
4646
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4647
                if (_LMItemNote != null)
4648
                {
4649
                    _LMItemNote.Commit();
4650
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4651
                    if (_LMAAttribute != null)
4652
                    {
4653
                        _LMAAttribute.set_Value(text.VALUE);
4654
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4655
                        _LMItemNote.Commit();
4656

    
4657

    
4658
                        double[] range = null;
4659
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4660
                        {
4661
                            double[] temp = null;
4662
                            GetSPPIDSymbolRange(labelPersist, ref temp);
4663
                            if (temp != null)
4664
                            {
4665
                                if (range == null)
4666
                                    range = temp;
4667
                                else
4668
                                {
4669
                                    range = new double[] {
4670
                                            Math.Min(range[0], temp[0]),
4671
                                            Math.Min(range[1], temp[1]),
4672
                                            Math.Max(range[2], temp[2]),
4673
                                            Math.Max(range[3], temp[3])
4674
                                        };
4675
                                }
4676
                            }
4677
                        }
4678
                        text.SPPID.Range = range;
4679

    
4680
                        if (_LMAAttribute != null)
4681
                            ReleaseCOMObjects(_LMAAttribute);
4682
                        if (_LMItemNote != null)
4683
                            ReleaseCOMObjects(_LMItemNote);
4684
                    }
4685

    
4686
                    TextCorrectModeling(text);
4687
                }
4688
            }
4689
            if (_LMSymbol != null)
4690
                ReleaseCOMObjects(_LMSymbol);
4691
        }
4692

    
4693
        private void AssociationTextModeling(Text text)
4694
        {
4695
            LMSymbol _LMSymbol = null;
4696
            LMConnector connectedLMConnector = null;
4697
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4698
            if (owner != null && owner.GetType() == typeof(Symbol))
4699
            {
4700
                Symbol symbol = owner as Symbol;
4701
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4702
                if (_LMSymbol != null)
4703
                {
4704
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4705
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4706
                    {
4707
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4708

    
4709
                        if (mapping != null)
4710
                        {
4711
                            double x = 0;
4712
                            double y = 0;
4713

    
4714
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4715
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4716
                            Array array = new double[] { 0, x, y };
4717
                            text.SPPID.SPPID_X = x;
4718
                            text.SPPID.SPPID_Y = y;
4719
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4720
                            if (_LMLabelPersist != null)
4721
                            {
4722
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4723
                                _LMLabelPersist.Commit();
4724
                                ReleaseCOMObjects(_LMLabelPersist);
4725
                            }
4726
                        }
4727
                    }
4728
                }
4729
            }
4730
            else if (owner != null && owner.GetType() == typeof(Line))
4731
            {
4732
                Line line = owner as Line;
4733
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4734
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
4735

    
4736
                if (connectedLMConnector != null)
4737
                {
4738
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4739
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4740
                    {
4741
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4742

    
4743
                        if (mapping != null)
4744
                        {
4745
                            double x = 0;
4746
                            double y = 0;
4747
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4748
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4749
                            Array array = new double[] { 0, x, y };
4750

    
4751
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4752
                            if (_LMLabelPersist != null)
4753
                            {
4754
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4755
                                _LMLabelPersist.Commit();
4756
                                ReleaseCOMObjects(_LMLabelPersist);
4757
                            }
4758
                        }
4759
                    }
4760
                }
4761
            }
4762
            if (_LMSymbol != null)
4763
                ReleaseCOMObjects(_LMSymbol);
4764
        }
4765

    
4766
        private void TextCorrectModeling(Text text)
4767
        {
4768
            if (text.SPPID.Range == null)
4769
                return;
4770

    
4771
            bool needRemodeling = false;
4772
            bool loop = true;
4773
            GridSetting gridSetting = GridSetting.GetInstance();
4774
            while (loop)
4775
            {
4776
                loop = false;
4777
                foreach (var overlapText in document.TEXTINFOS)
4778
                {
4779
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
4780
                        continue;
4781

    
4782
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
4783
                    {
4784
                        double percentX = 0;
4785
                        double percentY = 0;
4786
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
4787
                        {
4788
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
4789
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
4790
                        }
4791
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
4792
                        {
4793
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
4794
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
4795
                        }
4796

    
4797
                        double tempX = 0;
4798
                        double tempY = 0;
4799
                        bool overlapX = false;
4800
                        bool overlapY = false;
4801
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4802
                        if (percentX >= percentY)
4803
                        {
4804
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4805
                            double move = gridSetting.Length * count;
4806
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
4807
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
4808
                            needRemodeling = true;
4809
                            loop = true;
4810
                        }
4811
                        else
4812
                        {
4813
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4814
                            double move = gridSetting.Length * count;
4815
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
4816
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
4817
                            needRemodeling = true;
4818
                            loop = true;
4819
                        }
4820
                    }
4821
                }
4822
            }
4823
            
4824

    
4825
            if (needRemodeling)
4826
            {
4827
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
4828
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4829
                text.SPPID.RepresentationId = null;
4830

    
4831
                LMItemNote _LMItemNote = null;
4832
                LMAAttribute _LMAAttribute = null;
4833
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
4834
                if (_LMSymbol != null)
4835
                {
4836
                    _LMSymbol.Commit();
4837
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4838
                    if (_LMItemNote != null)
4839
                    {
4840
                        _LMItemNote.Commit();
4841
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4842
                        if (_LMAAttribute != null)
4843
                        {
4844
                            _LMAAttribute.set_Value(text.VALUE);
4845
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4846
                            _LMItemNote.Commit();
4847

    
4848
                            ReleaseCOMObjects(_LMAAttribute);
4849
                            ReleaseCOMObjects(_LMItemNote);
4850
                        }
4851
                    }
4852
                }
4853

    
4854
                ReleaseCOMObjects(symbol);
4855
                symbol = null;
4856
                ReleaseCOMObjects(_LMItemNote);
4857
                _LMItemNote = null;
4858
                ReleaseCOMObjects(_LMAAttribute);
4859
                _LMAAttribute = null;
4860
                ReleaseCOMObjects(_LMSymbol);
4861
                _LMSymbol = null;
4862
            }
4863
        }
4864

    
4865
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
4866
        {
4867
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
4868
            {
4869
                List<Text> texts = new List<Text>();
4870
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
4871
                LMRepresentation representation = targetLabel.RepresentationObject;
4872
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
4873
                if (targetLabel.RepresentationObject != null && symbol != null)
4874
                {
4875
                    double[] symbolRange = null;
4876
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
4877
                    if (symbolRange != null)
4878
                    {
4879
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
4880
                        {
4881
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
4882
                            if (findText != null)
4883
                            {
4884
                                double[] range = null;
4885
                                GetSPPIDSymbolRange(labelPersist, ref range);
4886
                                findText.SPPID.Range = range;
4887
                                texts.Add(findText);
4888
                            }
4889

    
4890
                            ReleaseCOMObjects(labelPersist);
4891
                        }
4892

    
4893
                        if (texts.Count > 0)
4894
                        {
4895
                            #region Sort Text By Y
4896
                            texts.Sort(SortTextByY);
4897
                            int SortTextByY(Text a, Text b)
4898
                            {
4899
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
4900
                            }
4901
                            #endregion
4902

    
4903
                            #region 첫번째 Text로 기준 맞춤
4904
                            for (int i = 0; i < texts.Count; i++)
4905
                            {
4906
                                if (i != 0)
4907
                                {
4908
                                    Text currentText = texts[i];
4909
                                    Text prevText = texts[i - 1];
4910
                                    double minY = prevText.SPPID.Range[1];
4911
                                    double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
4912
                                    double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
4913
                                    double _gapX = centerX - centerPrevX;
4914
                                    double _gapY = currentText.SPPID.Range[3] - minY;
4915
                                    MoveText(currentText, _gapX, _gapY);
4916
                                }
4917
                            }
4918
                            List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
4919
                            List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
4920
                            List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
4921
                            List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
4922
                            rangeMinX.Sort();
4923
                            rangeMinY.Sort();
4924
                            rangeMaxX.Sort();
4925
                            rangeMaxY.Sort();
4926
                            double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
4927
                            double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
4928
                            #endregion
4929

    
4930
                            Text correctBySymbol = texts[0];
4931
                            double textCenterX = (text.X1 + text.X2) / 2;
4932
                            double textCenterY = (text.Y1 + text.Y2) / 2;
4933
                            double originX = 0;
4934
                            double originY = 0;
4935
                            SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
4936
                            double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
4937
                            double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
4938
                            double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
4939

    
4940
                            double gapX = 0;
4941
                            double gapY = 0;
4942
                            if (angle < 45)
4943
                            {
4944
                                // Text 오른쪽
4945
                                if (textCenterX > originX)
4946
                                {
4947
                                    gapX = rangeMinX[0] - symbolRange[2];
4948
                                    gapY = allTextCenterY - symbolCenterY;
4949
                                }
4950
                                // Text 왼쪽
4951
                                else
4952
                                {
4953
                                    gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
4954
                                    gapY = allTextCenterY - symbolCenterY;
4955
                                }
4956
                            }
4957
                            else
4958
                            {
4959
                                // Text 아래쪽
4960
                                if (textCenterY > originY)
4961
                                {
4962
                                    gapX = allTextCenterX - symbolCenterX;
4963
                                    gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
4964
                                }
4965
                                // Text 위쪽
4966
                                else
4967
                                {
4968
                                    gapX = allTextCenterX - symbolCenterX;
4969
                                    gapY = rangeMinY[0] - symbolRange[3];
4970
                                }
4971
                            }
4972

    
4973
                            foreach (var item in texts)
4974
                            {
4975
                                MoveText(item, gapX, gapY);
4976
                                RemodelingAssociationText(item);
4977
                            }
4978
                        }
4979
                    }
4980
                }
4981

    
4982
                void MoveText(Text moveText, double x, double y)
4983
                {
4984
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
4985
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
4986
                    moveText.SPPID.Range = new double[] {
4987
                        moveText.SPPID.Range[0] - x,
4988
                        moveText.SPPID.Range[1]- y,
4989
                        moveText.SPPID.Range[2]- x,
4990
                        moveText.SPPID.Range[3]- y
4991
                    };
4992
                }
4993

    
4994
                endTexts.AddRange(texts);
4995

    
4996
                ReleaseCOMObjects(targetLabel);
4997
                targetLabel = null;
4998
                ReleaseCOMObjects(representation);
4999
                representation = null;
5000
            }
5001
        }
5002

    
5003
        private void RemodelingAssociationText(Text text)
5004
        {
5005
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5006
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5007
            removeLabel.Commit();
5008
            ReleaseCOMObjects(removeLabel);
5009
            removeLabel = null;
5010

    
5011
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5012
            if (owner != null && owner.GetType() == typeof(Symbol))
5013
            {
5014
                Symbol symbol = owner as Symbol;
5015
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5016
                if (_LMSymbol != null)
5017
                {
5018
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5019
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5020
                    {
5021
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5022

    
5023
                        if (mapping != null)
5024
                        {
5025
                            double x = 0;
5026
                            double y = 0;
5027

    
5028
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5029
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5030
                            if (_LMLabelPersist != null)
5031
                            {
5032
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5033
                                _LMLabelPersist.Commit();
5034
                            }
5035
                            ReleaseCOMObjects(_LMLabelPersist);
5036
                            _LMLabelPersist = null;
5037
                        }
5038
                    }
5039
                }
5040
                ReleaseCOMObjects(_LMSymbol);
5041
                _LMSymbol = null;
5042
            }
5043
        }
5044

    
5045
        /// <summary>
5046
        /// Note Modeling
5047
        /// </summary>
5048
        /// <param name="note"></param>
5049
        private void NoteModeling(Note note, List<Note> correctList)
5050
        {
5051
            LMSymbol _LMSymbol = null;
5052
            LMItemNote _LMItemNote = null;
5053
            LMAAttribute _LMAAttribute = null;
5054

    
5055
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5056
            {
5057
                double x = 0;
5058
                double y = 0;
5059

    
5060
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5061
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5062
                note.SPPID.SPPID_X = x;
5063
                note.SPPID.SPPID_Y = y;
5064

    
5065
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5066
                if (_LMSymbol != null)
5067
                {
5068
                    _LMSymbol.Commit();
5069
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5070
                    if (_LMItemNote != null)
5071
                    {
5072
                        _LMItemNote.Commit();
5073
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5074
                        if (_LMAAttribute != null)
5075
                        {
5076
                            _LMAAttribute.set_Value(note.VALUE);
5077
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5078

    
5079
                            double[] range = null;
5080
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5081
                            {
5082
                                double[] temp = null;
5083
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5084
                                if (temp != null)
5085
                                {
5086
                                    if (range == null)
5087
                                        range = temp;
5088
                                    else
5089
                                    {
5090
                                        range = new double[] {
5091
                                            Math.Min(range[0], temp[0]),
5092
                                            Math.Min(range[1], temp[1]),
5093
                                            Math.Max(range[2], temp[2]),
5094
                                            Math.Max(range[3], temp[3])
5095
                                        };
5096
                                    }
5097
                                }
5098
                            }
5099
                            if (range != null)
5100
                                correctList.Add(note);
5101
                            note.SPPID.Range = range;
5102

    
5103

    
5104
                            _LMItemNote.Commit();
5105
                        }
5106
                    }
5107
                }
5108
            }
5109

    
5110
            if (_LMAAttribute != null)
5111
                ReleaseCOMObjects(_LMAAttribute);
5112
            if (_LMItemNote != null)
5113
                ReleaseCOMObjects(_LMItemNote);
5114
            if (_LMSymbol != null)
5115
                ReleaseCOMObjects(_LMSymbol);
5116
        }
5117

    
5118
        private void NoteCorrectModeling(Note note, List<Note> endList)
5119
        {
5120
            bool needRemodeling = false;
5121
            bool loop = true;
5122
            GridSetting gridSetting = GridSetting.GetInstance();
5123
            while (loop)
5124
            {
5125
                loop = false;
5126
                foreach (var overlap in endList)
5127
                {
5128
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5129
                    {
5130
                        double tempX = 0;
5131
                        double tempY = 0;
5132
                        bool overlapX = false;
5133
                        bool overlapY = false;
5134
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5135
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5136
                        if (overlapY && angle >= 45)
5137
                        {
5138
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5139
                            double move = gridSetting.Length * count;
5140
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5141
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5142
                            needRemodeling = true;
5143
                            loop = true;
5144
                        }
5145
                        if (overlapX && angle <= 45)
5146
                        {
5147
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5148
                            double move = gridSetting.Length * count;
5149
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5150
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5151
                            needRemodeling = true;
5152
                            loop = true;
5153
                        }
5154
                    }
5155
                }
5156
            }
5157

    
5158

    
5159
            if (needRemodeling)
5160
            {
5161
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5162
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5163
                note.SPPID.RepresentationId = null;
5164

    
5165
                LMItemNote _LMItemNote = null;
5166
                LMAAttribute _LMAAttribute = null;
5167
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5168
                if (_LMSymbol != null)
5169
                {
5170
                    _LMSymbol.Commit();
5171
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5172
                    if (_LMItemNote != null)
5173
                    {
5174
                        _LMItemNote.Commit();
5175
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5176
                        if (_LMAAttribute != null)
5177
                        {
5178
                            _LMAAttribute.set_Value(note.VALUE);
5179
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5180
                            _LMItemNote.Commit();
5181

    
5182
                            ReleaseCOMObjects(_LMAAttribute);
5183
                            ReleaseCOMObjects(_LMItemNote);
5184
                        }
5185
                    }
5186
                }
5187

    
5188
                ReleaseCOMObjects(symbol);
5189
                symbol = null;
5190
                ReleaseCOMObjects(_LMItemNote);
5191
                _LMItemNote = null;
5192
                ReleaseCOMObjects(_LMAAttribute);
5193
                _LMAAttribute = null;
5194
                ReleaseCOMObjects(_LMSymbol);
5195
                _LMSymbol = null;
5196
            }
5197

    
5198
            endList.Add(note);
5199
        }
5200

    
5201
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5202
        {
5203
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5204
            if (modelItem != null)
5205
            {
5206
                foreach (LMRepresentation rep in modelItem.Representations)
5207
                {
5208
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5209
                    {
5210
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5211
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5212
                        {
5213
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5214
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5215
                            if (modelItemIds.Count == 1)
5216
                            {
5217
                                string joinModelItemId = modelItemIds[0];
5218
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5219
                                if (survivorId != null)
5220
                                    break;
5221
                            }
5222
                        }
5223
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5224
                        {
5225
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5226
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5227
                            if (modelItemIds.Count == 1)
5228
                            {
5229
                                string joinModelItemId = modelItemIds[0];
5230
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5231
                                if (survivorId != null)
5232
                                    break;
5233
                            }
5234
                        }
5235
                    }
5236
                }
5237
            }
5238
        }
5239

    
5240
        /// <summary>
5241
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5242
        /// </summary>
5243
        /// <param name="x"></param>
5244
        /// <param name="y"></param>
5245
        /// <param name="originX"></param>
5246
        /// <param name="originY"></param>
5247
        /// <param name="SPPIDLabelLocation"></param>
5248
        /// <param name="location"></param>
5249
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5250
        {
5251
            if (location == Location.None)
5252
            {
5253
                x = originX;
5254
                y = originY;
5255
            }
5256
            else
5257
            {
5258
                if (location.HasFlag(Location.Center))
5259
                {
5260
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5261
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5262
                }
5263

    
5264
                if (location.HasFlag(Location.Left))
5265
                    x = SPPIDLabelLocation.X1;
5266
                else if (location.HasFlag(Location.Right))
5267
                    x = SPPIDLabelLocation.X2;
5268

    
5269
                if (location.HasFlag(Location.Down))
5270
                    y = SPPIDLabelLocation.Y1;
5271
                else if (location.HasFlag(Location.Up))
5272
                    y = SPPIDLabelLocation.Y2;
5273
            }
5274
        }
5275

    
5276
        /// <summary>
5277
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5278
        /// 1. Angle Valve
5279
        /// 2. 3개로 이루어진 Symbol Group
5280
        /// </summary>
5281
        /// <returns></returns>
5282
        private List<Symbol> GetPrioritySymbol()
5283
        {
5284
            DataTable symbolTable = document.SymbolTable;
5285
            // List에 순서대로 쌓는다.
5286
            List<Symbol> symbols = new List<Symbol>();
5287

    
5288
            // Angle Valve 부터
5289
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5290
            {
5291
                if (!symbols.Contains(symbol))
5292
                {
5293
                    double originX = 0;
5294
                    double originY = 0;
5295

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

    
5300
                    SlopeType slopeType1 = SlopeType.None;
5301
                    SlopeType slopeType2 = SlopeType.None;
5302
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5303
                    {
5304
                        double connectorX = 0;
5305
                        double connectorY = 0;
5306
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5307
                        if (slopeType1 == SlopeType.None)
5308
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5309
                        else
5310
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5311
                    }
5312

    
5313
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5314
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5315
                        symbols.Add(symbol);
5316
                }
5317
            }
5318

    
5319
            List<Symbol> tempSymbols = new List<Symbol>();
5320
            // Conn 갯수 기준
5321
            foreach (var item in document.SYMBOLS)
5322
            {
5323
                if (!symbols.Contains(item))
5324
                    tempSymbols.Add(item);
5325
            }
5326
            tempSymbols.Sort(SortSymbolPriority);
5327
            symbols.AddRange(tempSymbols);
5328

    
5329
            return symbols;
5330
        }
5331

    
5332
        private void SetPriorityLine(List<Line> lines)
5333
        {
5334
            lines.Sort(SortLinePriority);
5335

    
5336
            int SortLinePriority(Line a, Line b)
5337
            {
5338
                // Branch 없는것부터
5339
                int branchRetval = CompareBranchLine(a, b);
5340
                if (branchRetval != 0)
5341
                {
5342
                    return branchRetval;
5343
                }
5344
                else
5345
                {
5346
                    // Symbol 연결 갯수
5347
                    int connSymbolRetval = CompareConnSymbol(a, b);
5348
                    if (connSymbolRetval != 0)
5349
                    {
5350
                        return connSymbolRetval;
5351
                    }
5352
                    else
5353
                    {
5354
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5355
                        int connItemRetval = CompareConnItem(a, b);
5356
                        if (connItemRetval != 0)
5357
                        {
5358
                            return connItemRetval;
5359
                        }
5360
                        else
5361
                        {
5362
                            // ConnectedItem이 없는것
5363
                            int noneConnRetval = CompareNoneConn(a, b);
5364
                            if (noneConnRetval != 0)
5365
                            {
5366
                                return noneConnRetval;
5367
                            }
5368
                            else
5369
                            {
5370

    
5371
                            }
5372
                        }
5373
                    }
5374
                }
5375

    
5376
                return 0;
5377
            }
5378

    
5379
            int CompareNotSegmentLine(Line a, Line b)
5380
            {
5381
                List<Connector> connectorsA = a.CONNECTORS
5382
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5383
                    .ToList();
5384

    
5385
                List<Connector> connectorsB = b.CONNECTORS
5386
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5387
                    .ToList();
5388

    
5389
                // 오름차순
5390
                return connectorsB.Count.CompareTo(connectorsA.Count);
5391
            }
5392

    
5393
            int CompareConnSymbol(Line a, Line b)
5394
            {
5395
                List<Connector> connectorsA = a.CONNECTORS
5396
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5397
                    .ToList();
5398

    
5399
                List<Connector> connectorsB = b.CONNECTORS
5400
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5401
                    .ToList();
5402

    
5403
                // 오름차순
5404
                return connectorsB.Count.CompareTo(connectorsA.Count);
5405
            }
5406

    
5407
            int CompareConnItem(Line a, Line b)
5408
            {
5409
                List<Connector> connectorsA = a.CONNECTORS
5410
                    .Where(conn => conn.ConnectedObject != null && 
5411
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5412
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5413
                    .ToList();
5414

    
5415
                List<Connector> connectorsB = b.CONNECTORS
5416
                    .Where(conn => conn.ConnectedObject != null &&
5417
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5418
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5419
                    .ToList();
5420

    
5421
                // 오름차순
5422
                return connectorsB.Count.CompareTo(connectorsA.Count);
5423
            }
5424

    
5425
            int CompareBranchLine(Line a, Line b)
5426
            {
5427
                List<Connector> connectorsA = a.CONNECTORS
5428
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5429
                    .ToList();
5430
                List<Connector> connectorsB = b.CONNECTORS
5431
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5432
                    .ToList();
5433

    
5434
                // 내림차순
5435
                return connectorsA.Count.CompareTo(connectorsB.Count);
5436
            }
5437

    
5438
            int CompareNoneConn(Line a, Line b)
5439
            {
5440
                List<Connector> connectorsA = a.CONNECTORS
5441
                    .Where(conn => conn.ConnectedObject == null)
5442
                    .ToList();
5443

    
5444
                List<Connector> connectorsB = b.CONNECTORS
5445
                    .Where(conn => conn.ConnectedObject == null)
5446
                    .ToList();
5447

    
5448
                // 오름차순
5449
                return connectorsB.Count.CompareTo(connectorsA.Count);
5450
            }
5451
        }
5452

    
5453
        private void SortText(List<Text> texts)
5454
        {
5455
            texts.Sort(Sort);
5456

    
5457
            int Sort(Text a, Text b)
5458
            {
5459
                int yRetval = CompareY(a, b);
5460
                if (yRetval != 0)
5461
                {
5462
                    return yRetval;
5463
                }
5464
                else
5465
                {
5466
                    return CompareX(a, b);
5467
                }
5468
            }
5469

    
5470
            int CompareY(Text a, Text b)
5471
            {
5472
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5473
            }
5474

    
5475
            int CompareX(Text a, Text b)
5476
            {
5477
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5478
            }
5479
        }
5480
        private void SortNote(List<Note> notes)
5481
        {
5482
            notes.Sort(Sort);
5483

    
5484
            int Sort(Note a, Note b)
5485
            {
5486
                int yRetval = CompareY(a, b);
5487
                if (yRetval != 0)
5488
                {
5489
                    return yRetval;
5490
                }
5491
                else
5492
                {
5493
                    return CompareX(a, b);
5494
                }
5495
            }
5496

    
5497
            int CompareY(Note a, Note b)
5498
            {
5499
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5500
            }
5501

    
5502
            int CompareX(Note a, Note b)
5503
            {
5504
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5505
            }
5506
        }
5507

    
5508
        private void SortBranchLines()
5509
        {
5510
            BranchLines.Sort(SortBranchLine);
5511
            int SortBranchLine(Line a, Line b)
5512
            {
5513
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5514
                 x.ConnectedObject.GetType() == typeof(Line) &&
5515
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
5516
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5517

    
5518
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5519
                 x.ConnectedObject.GetType() == typeof(Line) &&
5520
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
5521
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5522

    
5523
                // 내림차순
5524
                return countA.CompareTo(countB);
5525
            }
5526
        }
5527

    
5528
        private static int SortSymbolPriority(Symbol a, Symbol b)
5529
        {
5530
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5531
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5532
            int retval = countB.CompareTo(countA);
5533
            if (retval != 0)
5534
                return retval;
5535
            else
5536
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
5537
        }
5538

    
5539
        private string GetSPPIDFileName(LMModelItem modelItem)
5540
        {
5541
            string symbolPath = null;
5542
            foreach (LMRepresentation rep in modelItem.Representations)
5543
            {
5544
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5545
                {
5546
                    symbolPath = rep.get_FileName();
5547
                    break;
5548
                }
5549
            }
5550
            return symbolPath;
5551
        }
5552

    
5553
        private string GetSPPIDFileName(string modelItemId)
5554
        {
5555
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5556
            string symbolPath = null;
5557
            foreach (LMRepresentation rep in modelItem.Representations)
5558
            {
5559
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5560
                {
5561
                    symbolPath = rep.get_FileName();
5562
                    break;
5563
                }
5564
            }
5565
            ReleaseCOMObjects(modelItem);
5566
            return symbolPath;
5567
        }
5568

    
5569
        /// <summary>
5570
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
5571
        /// </summary>
5572
        /// <param name="graphicOID"></param>
5573
        /// <param name="milliseconds"></param>
5574
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
5575
        {
5576
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
5577
            {
5578
                double minX = 0;
5579
                double minY = 0;
5580
                double maxX = 0;
5581
                double maxY = 0;
5582
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
5583
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
5584

    
5585
                Thread.Sleep(milliseconds);
5586
            }
5587
        }
5588

    
5589
        /// <summary>
5590
        /// ComObject를 Release
5591
        /// </summary>
5592
        /// <param name="objVars"></param>
5593
        public void ReleaseCOMObjects(params object[] objVars)
5594
        {
5595
            if (objVars != null)
5596
            {
5597
                int intNewRefCount = 0;
5598
                foreach (object obj in objVars)
5599
                {
5600
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
5601
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
5602
                }
5603
            }
5604
        }
5605

    
5606
        /// IDisposable 구현
5607
        ~AutoModeling()
5608
        {
5609
            this.Dispose(false);
5610
        }
5611

    
5612
        private bool disposed;
5613
        public void Dispose()
5614
        {
5615
            this.Dispose(true);
5616
            GC.SuppressFinalize(this);
5617
        }
5618

    
5619
        protected virtual void Dispose(bool disposing)
5620
        {
5621
            if (this.disposed) return;
5622
            if (disposing)
5623
            {
5624
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
5625
            }
5626
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
5627
            this.disposed = true;
5628
        }
5629
    }
5630
}
클립보드 이미지 추가 (최대 크기: 500 MB)