프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 238eb5d2

이력 | 보기 | 이력해설 | 다운로드 (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.AddSymbolTarget(_TargetItem, lineX, lineY);
1181
                        placeRunInputs.AddPoint(-1, -1);
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
                        attribute.set_Value("End 1 is upstream (Inlet)");
2180
                        modelItem.Commit();
2181
                    }
2182
                    ReleaseCOMObjects(modelItem);
2183
                    modelItem = null;
2184
                }
2185
                else if (!isBranchModeling)
2186
                {
2187
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2188
                }
2189

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

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

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

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

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

    
2242
                ReleaseCOMObjects(modelItem);
2243
            }
2244
        }
2245

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2591
            ReleaseCOMObjects(modelItem);
2592
        }
2593

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

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

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

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

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

    
2657
                    break;
2658
                }
2659
            }
2660

    
2661
            return _LMSymbol;
2662
        }
2663

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

    
2680
            return null;
2681
        }
2682

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

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

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

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

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

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

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

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

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

    
2798
            return newConnector;
2799
        }
2800

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2979
            }
2980

    
2981
            return targetConnector;
2982
        }
2983

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

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

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

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

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

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

    
3091
            return result;
3092
        }
3093

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

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

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

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

    
3140
                    ReleaseCOMObjects(_LMConnector);
3141
                }
3142
            }
3143

    
3144

    
3145
            return result;
3146
        }
3147

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3317

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

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

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

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

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

    
3350

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

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

    
3377

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

    
3386
                return findResult;
3387
            }
3388
        }
3389

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

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

    
3430
                ReleaseCOMObjects(modelItem);
3431
            }
3432

    
3433
            return connectorVertices;
3434
        }
3435

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

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

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

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

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

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

    
3542
            return targetConnector;
3543
        }
3544

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

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

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

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

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

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

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

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

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

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

    
3639
                GridSetting gridSetting = GridSetting.GetInstance();
3640

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

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

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

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

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

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

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

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

    
3803
            return targetConnector;
3804
        }
3805

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

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

    
3820
                ReleaseCOMObjects(modelItem);
3821
            }
3822

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

    
3829
            return result;
3830
        }
3831

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

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

    
3861
            return result;
3862
        }
3863

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

    
3879
            return result;
3880
        }
3881

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

    
3896
            return result;
3897
        }
3898

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4089

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

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

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

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

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

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

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

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

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

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

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

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

    
4300
                    ReleaseCOMObjects(targetLMConnector);
4301
                }
4302
            }
4303

    
4304

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4656

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4889
                            ReleaseCOMObjects(labelPersist);
4890
                        }
4891

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

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

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

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

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

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

    
4993
                endTexts.AddRange(texts);
4994

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

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

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

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

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

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

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

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

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

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

    
5102

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

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

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

    
5157

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

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

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

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

    
5197
            endList.Add(note);
5198
        }
5199

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

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

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

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

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

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

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

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

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

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

    
5328
            return symbols;
5329
        }
5330

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

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

    
5370
                            }
5371
                        }
5372
                    }
5373
                }
5374

    
5375
                return 0;
5376
            }
5377

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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