프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ f14b4e3b

이력 | 보기 | 이력해설 | 다운로드 (266 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, 24);
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
                    // Check FlowDirection
111
                    RunFlowDirection();
112
                    // EndBreak Modeling
113
                    RunEndBreakModeling();
114
                    // SpecBreak Modeling
115
                    RunSpecBreakModeling();
116
                    //Line Number Modeling
117
                    RunLineNumberModeling();
118
                    // Note Modeling
119
                    RunNoteModeling();
120
                    // Text Modeling
121
                    RunTextModeling();
122
                    // Input LineNumber Attribute
123
                    RunInputLineNumberAttribute();
124
                    // Input Symbol Attribute
125
                    RunInputSymbolAttribute();
126
                    // Input SpecBreak Attribute
127
                    RunInputSpecBreakAttribute();
128
                    // Input EndBreak Attribute
129
                    RunInputEndBreakAttribute();
130
                    // Label Symbol Modeling
131
                    RunLabelSymbolModeling();
132
                    // Correct Text
133
                    RunCorrectAssociationText();
134

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

    
160
                Log.Write("End Modeling");
161
                radApp.ActiveWindow.Fit();
162

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

    
180
                ReleaseCOMObjects(dataSource);
181
                dataSource = null;
182
                ReleaseCOMObjects(_placement);
183
                _placement = null;
184

    
185
                Thread.Sleep(1000);
186
            }
187
        }
188

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

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

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

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

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

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

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

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

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

    
506
                LMRelationships relationships = new LMRelationships();
507
                relationships.Collect(dataSource, Filter: filter);
508

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

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

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

    
673
            foreach (var line in document.LINES)
674
                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
675
        }
676
        private void RunJoinRun()
677
        {
678
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
679
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
680
            List<string> endModelID = new List<string>();
681
            foreach (var line in document.LINES)
682
            {
683
                if (!endModelID.Contains(line.SPPID.ModelItemId))
684
                {
685
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
686
                    {
687
                        string survivorId = string.Empty;
688
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
689
                        if (string.IsNullOrEmpty(survivorId))
690
                        {
691
                            endModelID.Add(line.SPPID.ModelItemId);
692
                        }
693
                    }
694
                }
695
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
696
            }
697
        }
698
        private void RunLineNumberModeling()
699
        {
700
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
701
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
702
            foreach (var item in document.LINENUMBERS)
703
            {
704
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
705
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
706
                {
707
                    ReleaseCOMObjects(label);
708
                    item.SPPID.RepresentationId = null;
709
                    LineNumberModeling(item);
710
                }
711
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
712
            }
713
        }
714
        private void RunFlowDirection()
715
        {
716
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, 
717
                document.LINES.Count + ZeroLengthModelItemID.Count + ZeroLengthModelItemIDReverse.Count + ZeroLengthSymbolToSymbolModelItemID.Count);
718
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Check Flow Direction");
719
            foreach (var line in document.LINES)
720
            {
721
                if (!string.IsNullOrEmpty(line.SPPID.ModelItemId))
722
                {
723
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
724
                    if (modelItem != null && modelItem.get_ItemStatus() == "Active")
725
                    {
726
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
727
                        if (attribute != null)
728
                        {
729
                            attribute.set_Value("End 1 is upstream (Inlet)");
730
                            modelItem.Commit();
731
                        }
732

    
733
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
734

    
735
                        ReleaseCOMObjects(modelItem);
736
                        modelItem = null;
737
                    }
738
                }
739

    
740
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
741
            }
742
            foreach (var modelId in ZeroLengthModelItemID)
743
            {
744
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
745
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
746
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
747
                {
748
                    attribute.set_Value("End 1 is upstream (Inlet)");
749
                    zeroLengthModelItem.Commit();
750
                }
751

    
752
                SetFlowDirectionByLine(modelId);
753

    
754
                ReleaseCOMObjects(zeroLengthModelItem);
755
                zeroLengthModelItem = null;
756

    
757
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
758
            }
759
            foreach (var modelId in ZeroLengthModelItemIDReverse)
760
            {
761
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
762
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
763
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
764
                {
765
                    attribute.set_Value("End 1 is downstream (Outlet)");
766
                    zeroLengthModelItem.Commit();
767
                }
768

    
769
                SetFlowDirectionByLine(modelId);
770

    
771
                ReleaseCOMObjects(zeroLengthModelItem);
772
                zeroLengthModelItem = null;
773

    
774
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
775
            }
776
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
777
            {
778
                SetFlowDirectionByLine(modelId);
779
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
780
            }
781

    
782
            void SetFlowDirectionByLine(string lineModelItemID)
783
            {
784
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
785
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
786
                {
787
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
788
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
789
                    {
790
                        string sFlowDirection = attribute.get_Value().ToString();
791
                        foreach (LMRepresentation rep in modelItem.Representations)
792
                        {
793
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
794
                            {
795
                                LMConnector connector = dataSource.GetConnector(rep.Id);
796

    
797
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
798
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
799
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
800
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
801

    
802
                                ReleaseCOMObjects(connector);
803
                            }
804
                        }
805
                    }
806
                    ReleaseCOMObjects(modelItem);
807
                    modelItem = null;
808
                }
809

    
810
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
811
                {
812
                    // Item2가 Symbol
813
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
814
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
815
                    {
816
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
817
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
818
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
819

    
820
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
821

    
822
                        symbolModelItem.Commit();
823
                        ReleaseCOMObjects(symbolModelItem);
824
                        symbolModelItem = null;
825
                    }
826
                    // Item1이 Symbol
827
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
828
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
829
                    {
830
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
831
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
832
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
833

    
834
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
835

    
836
                        symbolModelItem.Commit();
837
                        ReleaseCOMObjects(symbolModelItem);
838
                        symbolModelItem = null;
839
                    }
840
                }
841

    
842
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
843
                {
844
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
845
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
846
                    if (attribute != null)
847
                    {
848
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
849
                            attribute.set_Value("End 1 is downstream (Outlet)");
850
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
851
                            attribute.set_Value("End 1 is upstream (Inlet)");
852
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
853
                            attribute.set_Value("End 1 is upstream (Inlet)");
854
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
855
                            attribute.set_Value("End 1 is downstream (Outlet)");
856
                    }
857
                }
858
            }
859
        }
860
        private void RunNoteModeling()
861
        {
862
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
863
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
864
            List<Note> correctList = new List<Note>();
865
            foreach (var item in document.NOTES)
866
                try
867
                {
868
                    NoteModeling(item, correctList);
869
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
870
                }
871
                catch (Exception ex)
872
                {
873
                    Log.Write("Error in NoteModeling");
874
                    Log.Write("UID : " + item.UID);
875
                    Log.Write(ex.Message);
876
                    Log.Write(ex.StackTrace);
877
                }
878

    
879
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
880
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
881
            SortNote(correctList);
882
            List<Note> endList = new List<Note>();
883
            if (correctList.Count > 0)
884
                endList.Add(correctList[0]);
885
            foreach (var item in correctList)
886
                try
887
                {
888
                    if (!endList.Contains(item))
889
                        NoteCorrectModeling(item, endList);
890
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
891
                }
892
                catch (Exception ex)
893
                {
894
                    Log.Write("Error in NoteModeling");
895
                    Log.Write("UID : " + item.UID);
896
                    Log.Write(ex.Message);
897
                    Log.Write(ex.StackTrace);
898
                }
899
        }
900
        private void RunTextModeling()
901
        {
902
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
903
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
904
            SortText(document.TEXTINFOS);
905
            foreach (var item in document.TEXTINFOS)
906
                try
907
                {
908
                    if (item.ASSOCIATION)
909
                        AssociationTextModeling(item);
910
                    else
911
                        NormalTextModeling(item);
912
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
913
                }
914
                catch (Exception ex)
915
                {
916
                    Log.Write("Error in TextModeling");
917
                    Log.Write("UID : " + item.UID);
918
                    Log.Write(ex.Message);
919
                    Log.Write(ex.StackTrace);
920
                }
921
        }
922
        private void RunInputLineNumberAttribute()
923
        {
924
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
925
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
926
            List<string> endLine = new List<string>();
927
            foreach (var item in document.LINENUMBERS)
928
                try
929
                {
930
                    InputLineNumberAttribute(item, endLine);
931
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
932
                }
933
                catch (Exception ex)
934
                {
935
                    Log.Write("Error in InputLineNumberAttribute");
936
                    Log.Write("UID : " + item.UID);
937
                    Log.Write(ex.Message);
938
                    Log.Write(ex.StackTrace);
939
                }
940
        }
941
        private void RunInputSymbolAttribute()
942
        {
943
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
944
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
945
            foreach (var item in document.SYMBOLS)
946
                try
947
                {
948
                    InputSymbolAttribute(item, item.ATTRIBUTES);
949
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
950
                }
951
                catch (Exception ex)
952
                {
953
                    Log.Write("Error in InputSymbolAttribute");
954
                    Log.Write("UID : " + item.UID);
955
                    Log.Write(ex.Message);
956
                    Log.Write(ex.StackTrace);
957
                }
958
        }
959
        private void RunInputSpecBreakAttribute()
960
        {
961
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
962
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
963
            foreach (var item in document.SpecBreaks)
964
                try
965
                {
966
                    InputSpecBreakAttribute(item);
967
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
968
                }
969
                catch (Exception ex)
970
                {
971
                    Log.Write("Error in InputSpecBreakAttribute");
972
                    Log.Write("UID : " + item.UID);
973
                    Log.Write(ex.Message);
974
                    Log.Write(ex.StackTrace);
975
                }
976
        }
977
        private void RunInputEndBreakAttribute()
978
        {
979
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
980
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
981
            foreach (var item in document.EndBreaks)
982
                try
983
                {
984
                    InputEndBreakAttribute(item);
985
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
986
                }
987
                catch (Exception ex)
988
                {
989
                    Log.Write("Error in RunInputEndBreakAttribute");
990
                    Log.Write("UID : " + item.UID);
991
                    Log.Write(ex.Message);
992
                    Log.Write(ex.StackTrace);
993
                }
994
        }
995
        private void RunLabelSymbolModeling()
996
        {
997
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
998
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
999
            foreach (var item in document.SYMBOLS)
1000
                try
1001
                {
1002
                    LabelSymbolModeling(item);
1003
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1004
                }
1005
                catch (Exception ex)
1006
                {
1007
                    Log.Write("Error in LabelSymbolModeling");
1008
                    Log.Write("UID : " + item.UID);
1009
                    Log.Write(ex.Message);
1010
                    Log.Write(ex.StackTrace);
1011
                }
1012
        }
1013
        private void RunCorrectAssociationText()
1014
        {
1015
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
1016
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
1017
            List<Text> endTexts = new List<Text>();
1018
            foreach (var item in document.TEXTINFOS)
1019
            {
1020
                try
1021
                {
1022
                    if (item.ASSOCIATION && !endTexts.Contains(item))
1023
                        AssociationTextCorrectModeling(item, endTexts);
1024
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1025
                }
1026
                catch (Exception ex)
1027
                {
1028
                    Log.Write("Error in RunCorrectAssociationText");
1029
                    Log.Write("UID : " + item.UID);
1030
                    Log.Write(ex.Message);
1031
                    Log.Write(ex.StackTrace);
1032
                }
1033
                
1034
            }
1035

    
1036
            foreach (var item in document.LINENUMBERS)
1037
            {
1038
                try
1039
                {
1040
                    LineNumberCorrectModeling(item);
1041
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1042
                }
1043
                catch (Exception ex)
1044
                {
1045
                    Log.Write("Error in RunCorrectAssociationText");
1046
                    Log.Write("UID : " + item.UID);
1047
                    Log.Write(ex.Message);
1048
                    Log.Write(ex.StackTrace);
1049
                }
1050
            }
1051
        }
1052
        /// <summary>
1053
        /// 도면 생성 메서드
1054
        /// </summary>
1055
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
1056
        {
1057
            Log.Write("------------------ Start create document ------------------");
1058
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
1059
            Log.Write("Drawing name : " + drawingName);
1060
            Log.Write("Drawing number : " + drawingNumber);
1061
            Thread.Sleep(1000);
1062
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
1063
            if (newDrawing != null)
1064
            {
1065
                document.SPPID_DrawingNumber = drawingNumber;
1066
                document.SPPID_DrawingName = drawingName;
1067
                Thread.Sleep(1000);
1068
                radApp.ActiveWindow.Fit();
1069
                Thread.Sleep(1000);
1070
                radApp.ActiveWindow.Zoom = 2000;
1071
                Thread.Sleep(2000);
1072

    
1073
                //current LMDrawing 가져오기
1074
                LMAFilter filter = new LMAFilter();
1075
                LMACriterion criterion = new LMACriterion();
1076
                filter.ItemType = "Drawing";
1077
                criterion.SourceAttributeName = "Name";
1078
                criterion.Operator = "=";
1079
                criterion.set_ValueAttribute(drawingName);
1080
                filter.get_Criteria().Add(criterion);
1081

    
1082
                LMDrawings drawings = new LMDrawings();
1083
                drawings.Collect(dataSource, Filter: filter);
1084

    
1085
                drawingID = ((dynamic)drawings).Nth(1).Id;
1086
                ReleaseCOMObjects(filter);
1087
                ReleaseCOMObjects(criterion);
1088
                ReleaseCOMObjects(drawings);
1089
                filter = null;
1090
                criterion = null;
1091
                drawings = null;
1092
            }
1093
            else
1094
                Log.Write("Fail Create Drawing");
1095

    
1096
            if (newDrawing != null)
1097
                return true;
1098
            else
1099
                return false;
1100
        }
1101

    
1102
        /// <summary>
1103
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1104
        /// </summary>
1105
        /// <param name="drawingName"></param>
1106
        /// <param name="drawingNumber"></param>
1107
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1108
        {
1109
            LMDrawings drawings = new LMDrawings();
1110
            drawings.Collect(dataSource);
1111

    
1112
            List<string> drawingNameList = new List<string>();
1113
            List<string> drawingNumberList = new List<string>();
1114

    
1115
            foreach (LMDrawing item in drawings)
1116
            {
1117
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1118
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1119
            }
1120

    
1121
            int nameLength = drawingName.Length;
1122
            while (drawingNameList.Contains(drawingName))
1123
            {
1124
                if (nameLength == drawingName.Length)
1125
                    drawingName += "-1";
1126
                else
1127
                {
1128
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1129
                    drawingName = drawingName.Substring(0, nameLength + 1);
1130
                    drawingName += ++index;
1131
                }
1132
            }
1133

    
1134
            int numberLength = drawingNumber.Length;
1135
            while (drawingNameList.Contains(drawingNumber))
1136
            {
1137
                if (numberLength == drawingNumber.Length)
1138
                    drawingNumber += "-1";
1139
                else
1140
                {
1141
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1142
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1143
                    drawingNumber += ++index;
1144
                }
1145
            }
1146
            ReleaseCOMObjects(drawings);
1147
            drawings = null;
1148
        }
1149

    
1150
        /// <summary>
1151
        /// 도면 크기 구하는 메서드
1152
        /// </summary>
1153
        /// <returns></returns>
1154
        private bool DocumentCoordinateCorrection()
1155
        {
1156
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1157
            {
1158
                Log.Write("Setting Drawing X, Drawing Y");
1159
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1160
                Log.Write("Start coordinate correction");
1161
                document.CoordinateCorrection();
1162
                return true;
1163
            }
1164
            else
1165
            {
1166
                Log.Write("Need Drawing X, Y");
1167
                return false;
1168
            }
1169
        }
1170

    
1171
        /// <summary>
1172
        /// 심볼을 실제로 Modeling 메서드
1173
        /// </summary>
1174
        /// <param name="symbol">생성할 심볼</param>
1175
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1176
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1177
        {
1178
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1179
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1180
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1181
                return;
1182
            // 이미 모델링 됐을 경우
1183
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1184
                return;
1185

    
1186
            LMSymbol _LMSymbol = null;
1187

    
1188
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1189
            double x = symbol.SPPID.ORIGINAL_X;
1190
            double y = symbol.SPPID.ORIGINAL_Y;
1191
            int mirror = 0;
1192
            double angle = symbol.ANGLE;
1193

    
1194
            // OPC 일경우 180도 일때 Mirror
1195
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1196
                mirror = 1;
1197

    
1198
            // Mirror 계산
1199
            if (symbol.FLIP == 1)
1200
            {
1201
                mirror = 1;
1202
                angle += Math.PI;
1203
            }
1204

    
1205
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1206
            {
1207
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1208
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1209
                if (connector != null)
1210
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1211

    
1212
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1213
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1214
                if (temp != null)
1215
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1216
                ReleaseCOMObjects(temp);
1217
                temp = null;
1218

    
1219
                if (_LMSymbol != null && _TargetItem != null)
1220
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1221

    
1222
                ReleaseCOMObjects(_TargetItem);
1223
            }
1224
            else
1225
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1226

    
1227
            if (_LMSymbol != null)
1228
            {
1229
                _LMSymbol.Commit();
1230

    
1231
                // ConnCheck
1232
                List<string> ids = new List<string>();
1233
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1234
                {
1235
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1236
                        ids.Add(item.Id);
1237
                    ReleaseCOMObjects(item);
1238
                }
1239
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1240
                {
1241
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1242
                        ids.Add(item.Id);
1243
                    ReleaseCOMObjects(item);
1244
                }
1245

    
1246
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1247
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1248
                {
1249
                    double currentX = _LMSymbol.get_XCoordinate();
1250
                    double currentY = _LMSymbol.get_YCoordinate();
1251

    
1252

    
1253
                }
1254

    
1255
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1256
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1257
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1258

    
1259
                foreach (var item in symbol.ChildSymbols)
1260
                    CreateChildSymbol(item, _LMSymbol, symbol);
1261

    
1262
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1263
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1264

    
1265
                double[] range = null;
1266
                GetSPPIDSymbolRange(symbol, ref range);
1267
                symbol.SPPID.SPPID_Min_X = range[0];
1268
                symbol.SPPID.SPPID_Min_Y = range[1];
1269
                symbol.SPPID.SPPID_Max_X = range[2];
1270
                symbol.SPPID.SPPID_Max_Y = range[3];
1271

    
1272
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1273
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1274
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1275
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1276

    
1277
                ReleaseCOMObjects(_LMSymbol);
1278
            }
1279
        }
1280
        /// <summary>
1281
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1282
        /// Signal Point는 고려하지 않음
1283
        /// </summary>
1284
        /// <param name="symbol"></param>
1285
        /// <param name="_TargetItem"></param>
1286
        /// <param name="targetX"></param>
1287
        /// <param name="targetY"></param>
1288
        /// <returns></returns>
1289
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1290
        {
1291
            LMConnector tempConnector = null;
1292

    
1293
            List<Symbol> group = new List<Symbol>();
1294
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1295
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1296
            {
1297
                List<Connector> connectors = new List<Connector>();
1298
                foreach (var item in group)
1299
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1300
                /// Primary or Secondary Type Line만 고려
1301
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1302
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1303
                if (_connector != null)
1304
                {
1305
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1306
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1307
                    /// PipingPoint가 2개 이상만
1308
                    if (pointInfos.Count >= 2)
1309
                    {
1310
                        double lineX = 0;
1311
                        double lineY = 0;
1312
                        double length = 0;
1313
                        foreach (var item in pointInfos)
1314
                        {
1315
                            double tempX = item[1];
1316
                            double tempY = item[2];
1317

    
1318
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1319
                            if (calcDistance > length)
1320
                            {
1321
                                lineX = tempX;
1322
                                lineY = tempY;
1323
                            }
1324
                        }
1325

    
1326
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1327
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1328
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1329
                        placeRunInputs.AddPoint(-1, -1);
1330
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1331
                        if (tempConnector != null)
1332
                            tempConnector.Commit();
1333
                        ReleaseCOMObjects(_LMAItem);
1334
                        _LMAItem = null;
1335
                        ReleaseCOMObjects(placeRunInputs);
1336
                        placeRunInputs = null;
1337
                    }
1338
                }
1339
            }
1340

    
1341
            return tempConnector;
1342
        }
1343
        /// <summary>
1344
        /// Symbol의 PipingPoints를 구함
1345
        /// SignalPoint는 고려하지 않음
1346
        /// </summary>
1347
        /// <param name="symbol"></param>
1348
        /// <returns></returns>
1349
        private List<double[]> getPipingPoints(LMSymbol symbol)
1350
        {
1351
            LMModelItem modelItem = symbol.ModelItemObject;
1352
            LMPipingPoints pipingPoints = null;
1353
            if (modelItem.get_ItemTypeName() == "PipingComp")
1354
            {
1355
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1356
                pipingPoints = pipingComp.PipingPoints;
1357
                ReleaseCOMObjects(pipingComp);
1358
                pipingComp = null;
1359
            }
1360
            else if (modelItem.get_ItemTypeName() == "Instrument")
1361
            {
1362
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1363
                pipingPoints = instrument.PipingPoints;
1364
                ReleaseCOMObjects(instrument);
1365
                instrument = null;
1366
            }
1367
            else
1368
                Log.Write("다른 Type");
1369

    
1370
            List<double[]> info = new List<double[]>();
1371
            if (pipingPoints != null)
1372
            {
1373
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1374
                {
1375
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1376
                    {
1377
                        if (attribute.Name == "PipingPointNumber")
1378
                        {
1379
                            int index = Convert.ToInt32(attribute.get_Value());
1380
                            if (info.Find(loopX => loopX[0] == index) == null)
1381
                            {
1382
                                double x = 0;
1383
                                double y = 0;
1384
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1385
                                    info.Add(new double[] { index, x, y });
1386
                            }
1387
                        }
1388
                    }
1389
                }
1390
            }
1391
            ReleaseCOMObjects(modelItem);
1392
            modelItem = null;
1393
            ReleaseCOMObjects(pipingPoints);
1394
            pipingPoints = null;
1395

    
1396
            return info;
1397
        }
1398

    
1399
        private void RemoveSymbol(Symbol symbol)
1400
        {
1401
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1402
            {
1403
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1404
                if (_LMSymbol != null)
1405
                {
1406
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1407
                    ReleaseCOMObjects(_LMSymbol);
1408
                }
1409
            }
1410

    
1411
            symbol.SPPID.RepresentationId = string.Empty;
1412
            symbol.SPPID.ModelItemID = string.Empty;
1413
            symbol.SPPID.SPPID_X = double.NaN;
1414
            symbol.SPPID.SPPID_Y = double.NaN;
1415
            symbol.SPPID.SPPID_Min_X = double.NaN;
1416
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1417
            symbol.SPPID.SPPID_Max_X = double.NaN;
1418
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1419
        }
1420

    
1421
        private void RemoveSymbol(List<Symbol> symbols)
1422
        {
1423
            foreach (var symbol in symbols)
1424
            {
1425
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1426
                {
1427
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1428
                    if (_LMSymbol != null)
1429
                    {
1430
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1431
                        ReleaseCOMObjects(_LMSymbol);
1432
                    }
1433
                }
1434

    
1435
                symbol.SPPID.RepresentationId = string.Empty;
1436
                symbol.SPPID.ModelItemID = string.Empty;
1437
                symbol.SPPID.SPPID_X = double.NaN;
1438
                symbol.SPPID.SPPID_Y = double.NaN;
1439
                symbol.SPPID.SPPID_Min_X = double.NaN;
1440
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1441
                symbol.SPPID.SPPID_Max_X = double.NaN;
1442
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1443
            }
1444
        }
1445

    
1446
        /// <summary>
1447
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1448
        /// </summary>
1449
        /// <param name="targetConnector"></param>
1450
        /// <param name="targetSymbol"></param>
1451
        /// <param name="x"></param>
1452
        /// <param name="y"></param>
1453
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1454
        {
1455
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1456

    
1457
            double[] range = null;
1458
            List<double[]> points = new List<double[]>();
1459
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1460
            double x1 = range[0];
1461
            double y1 = range[1];
1462
            double x2 = range[2];
1463
            double y2 = range[3];
1464

    
1465
            // Origin 기준 Connector의 위치차이
1466
            double sceneX = 0;
1467
            double sceneY = 0;
1468
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1469
            double originX = 0;
1470
            double originY = 0;
1471
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1472
            double gapX = originX - sceneX;
1473
            double gapY = originY - sceneY;
1474

    
1475
            // SPPID Symbol과 ID2 심볼의 크기 차이
1476
            double sizeWidth = 0;
1477
            double sizeHeight = 0;
1478
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1479
            if (sizeWidth == 0 || sizeHeight == 0)
1480
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1481

    
1482
            double percentX = (x2 - x1) / sizeWidth;
1483
            double percentY = (y2 - y1) / sizeHeight;
1484

    
1485
            double SPPIDgapX = gapX * percentX;
1486
            double SPPIDgapY = gapY * percentY;
1487

    
1488
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1489
            double distance = double.MaxValue;
1490
            double[] resultPoint;
1491
            foreach (var point in points)
1492
            {
1493
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1494
                if (distance > result)
1495
                {
1496
                    distance = result;
1497
                    resultPoint = point;
1498
                    x = point[0];
1499
                    y = point[1];
1500
                }
1501
            }
1502

    
1503
            ReleaseCOMObjects(_TargetItem);
1504
        }
1505

    
1506
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1507
        {
1508
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1509
            if (index == 0)
1510
            {
1511
                x = targetLine.SPPID.START_X;
1512
                y = targetLine.SPPID.START_Y;
1513
            }
1514
            else
1515
            {
1516
                x = targetLine.SPPID.END_X;
1517
                y = targetLine.SPPID.END_Y;
1518
            }
1519
        }
1520

    
1521
        /// <summary>
1522
        /// SPPID Symbol의 Range를 구한다.
1523
        /// </summary>
1524
        /// <param name="symbol"></param>
1525
        /// <param name="range"></param>
1526
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1527
        {
1528
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1529
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1530
            double x1 = 0;
1531
            double y1 = 0;
1532
            double x2 = 0;
1533
            double y2 = 0;
1534
            symbol2d.Range(out x1, out y1, out x2, out y2);
1535
            range = new double[] { x1, y1, x2, y2 };
1536

    
1537
            for (int i = 1; i < int.MaxValue; i++)
1538
            {
1539
                double connX = 0;
1540
                double connY = 0;
1541
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1542
                    points.Add(new double[] { connX, connY });
1543
                else
1544
                    break;
1545
            }
1546

    
1547
            foreach (var childSymbol in symbol.ChildSymbols)
1548
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1549

    
1550
            ReleaseCOMObjects(_TargetItem);
1551
        }
1552

    
1553
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1554
        {
1555
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1556
            if (_TargetItem != null)
1557
            {
1558
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1559
                double x1 = 0;
1560
                double y1 = 0;
1561
                double x2 = 0;
1562
                double y2 = 0;
1563
                if (!bForGraphic)
1564
                {
1565
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1566
                    range = new double[] { x1, y1, x2, y2 };
1567
                }
1568
                else
1569
                {
1570
                    x1 = double.MaxValue;
1571
                    y1 = double.MaxValue;
1572
                    x2 = double.MinValue;
1573
                    y2 = double.MinValue;
1574
                    range = new double[] { x1, y1, x2, y2 };
1575

    
1576
                    foreach (var item in symbol2d.DrawingObjects)
1577
                    {
1578
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1579
                        {
1580
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1581
                            if (rangeObject.Layer == "Default")
1582
                            {
1583
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1584
                                range = new double[] {
1585
                                Math.Min(x1, range[0]),
1586
                                Math.Min(y1, range[1]),
1587
                                Math.Max(x2, range[2]),
1588
                                Math.Max(y2, range[3])
1589
                            };
1590
                            }
1591
                        }
1592
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1593
                        {
1594
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1595
                            if (rangeObject.Layer == "Default")
1596
                            {
1597
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1598
                                range = new double[] {
1599
                                Math.Min(x1, range[0]),
1600
                                Math.Min(y1, range[1]),
1601
                                Math.Max(x2, range[2]),
1602
                                Math.Max(y2, range[3])
1603
                            };
1604
                            }
1605
                        }
1606
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1607
                        {
1608
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1609
                            if (rangeObject.Layer == "Default")
1610
                            {
1611
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1612
                                range = new double[] {
1613
                                Math.Min(x1, range[0]),
1614
                                Math.Min(y1, range[1]),
1615
                                Math.Max(x2, range[2]),
1616
                                Math.Max(y2, range[3])
1617
                            };
1618
                            }
1619
                        }
1620
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1621
                        {
1622
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1623
                            if (rangeObject.Layer == "Default")
1624
                            {
1625
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1626
                                range = new double[] {
1627
                                Math.Min(x1, range[0]),
1628
                                Math.Min(y1, range[1]),
1629
                                Math.Max(x2, range[2]),
1630
                                Math.Max(y2, range[3])
1631
                            };
1632
                            }
1633
                        }
1634
                    }
1635
                }
1636

    
1637
                if (!bOnlySymbol)
1638
                {
1639
                    foreach (var childSymbol in symbol.ChildSymbols)
1640
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1641
                }
1642
                ReleaseCOMObjects(_TargetItem);
1643
            }
1644
        }
1645

    
1646
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1647
        {
1648
            if (labelPersist != null)
1649
            {
1650
                double x1 = double.MaxValue;
1651
                double y1 = double.MaxValue;
1652
                double x2 = double.MinValue;
1653
                double y2 = double.MinValue;
1654
                range = new double[] { x1, y1, x2, y2 };
1655

    
1656
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1657
                foreach (var item in dependency.DrawingObjects)
1658
                {
1659
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1660
                    if (textBox != null)
1661
                    {
1662
                        if (dependency != null)
1663
                        {
1664
                            double tempX1;
1665
                            double tempY1;
1666
                            double tempX2;
1667
                            double tempY2;
1668
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1669
                            x1 = Math.Min(x1, tempX1);
1670
                            y1 = Math.Min(y1, tempY1);
1671
                            x2 = Math.Max(x2, tempX2);
1672
                            y2 = Math.Max(y2, tempY2);
1673

    
1674
                            range = new double[] { x1, y1, x2, y2 };
1675
                        }
1676
                    }
1677
                }
1678
                
1679
            }
1680
        }
1681

    
1682
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1683
        {
1684
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1685
            foreach (var symbol in symbols)
1686
            {
1687
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1688
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1689
                double x1 = 0;
1690
                double y1 = 0;
1691
                double x2 = 0;
1692
                double y2 = 0;
1693
                symbol2d.Range(out x1, out y1, out x2, out y2);
1694

    
1695
                tempRange[0] = Math.Min(tempRange[0], x1);
1696
                tempRange[1] = Math.Min(tempRange[1], y1);
1697
                tempRange[2] = Math.Max(tempRange[2], x2);
1698
                tempRange[3] = Math.Max(tempRange[3], y2);
1699

    
1700
                foreach (var childSymbol in symbol.ChildSymbols)
1701
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1702

    
1703
                ReleaseCOMObjects(_TargetItem);
1704
            }
1705

    
1706
            range = tempRange;
1707
        }
1708

    
1709
        /// <summary>
1710
        /// Child Modeling 된 Symbol의 Range를 구한다.
1711
        /// </summary>
1712
        /// <param name="childSymbol"></param>
1713
        /// <param name="range"></param>
1714
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1715
        {
1716
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1717
            if (_ChildSymbol != null)
1718
            {
1719
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1720
                double x1 = 0;
1721
                double y1 = 0;
1722
                double x2 = 0;
1723
                double y2 = 0;
1724
                symbol2d.Range(out x1, out y1, out x2, out y2);
1725
                range[0] = Math.Min(range[0], x1);
1726
                range[1] = Math.Min(range[1], y1);
1727
                range[2] = Math.Max(range[2], x2);
1728
                range[3] = Math.Max(range[3], y2);
1729

    
1730
                for (int i = 1; i < int.MaxValue; i++)
1731
                {
1732
                    double connX = 0;
1733
                    double connY = 0;
1734
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1735
                        points.Add(new double[] { connX, connY });
1736
                    else
1737
                        break;
1738
                }
1739

    
1740
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1741
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1742

    
1743
                ReleaseCOMObjects(_ChildSymbol);
1744
            }
1745
        }
1746

    
1747
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1748
        {
1749
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1750
            if (_ChildSymbol != null)
1751
            {
1752
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1753
                double x1 = 0;
1754
                double y1 = 0;
1755
                double x2 = 0;
1756
                double y2 = 0;
1757
                symbol2d.Range(out x1, out y1, out x2, out y2);
1758
                range[0] = Math.Min(range[0], x1);
1759
                range[1] = Math.Min(range[1], y1);
1760
                range[2] = Math.Max(range[2], x2);
1761
                range[3] = Math.Max(range[3], y2);
1762

    
1763
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1764
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1765
                ReleaseCOMObjects(_ChildSymbol);
1766
            }
1767
        }
1768

    
1769
        /// <summary>
1770
        /// Label Symbol Modeling
1771
        /// </summary>
1772
        /// <param name="symbol"></param>
1773
        private void LabelSymbolModeling(Symbol symbol)
1774
        {
1775
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1776
            {
1777
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1778
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1779
                    return;
1780
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1781

    
1782
                string symbolUID = itemAttribute.VALUE;
1783
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1784
                if (targetItem != null &&
1785
                    (targetItem.GetType() == typeof(Symbol) ||
1786
                    targetItem.GetType() == typeof(Equipment)))
1787
                {
1788
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1789
                    string sRep = null;
1790
                    if (targetItem.GetType() == typeof(Symbol))
1791
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1792
                    else if (targetItem.GetType() == typeof(Equipment))
1793
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1794
                    if (!string.IsNullOrEmpty(sRep))
1795
                    {
1796
                        // LEADER Line 검사
1797
                        bool leaderLine = false;
1798
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1799
                        if (symbolMapping != null)
1800
                            leaderLine = symbolMapping.LEADERLINE;
1801

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

    
1806
                        //Leader 선 센터로
1807
                        if (_LMLabelPresist != null)
1808
                        {
1809
                            // Target Item에 Label의 Attribute Input
1810
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1811

    
1812
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1813
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1814
                            if (dependency != null)
1815
                            {
1816
                                bool result = false;
1817
                                foreach (var attributes in dependency.AttributeSets)
1818
                                {
1819
                                    foreach (var attribute in attributes)
1820
                                    {
1821
                                        string name = attribute.Name;
1822
                                        string value = attribute.GetValue().ToString();
1823
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1824
                                        {
1825
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1826
                                            {
1827
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1828
                                                {
1829
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1830
                                                    double prevX = _TargetItem.get_XCoordinate();
1831
                                                    double prevY = _TargetItem.get_YCoordinate();
1832
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1833
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1834
                                                    result = true;
1835
                                                    break;
1836
                                                }
1837
                                            }
1838
                                        }
1839

    
1840
                                        if (result)
1841
                                            break;
1842
                                    }
1843

    
1844
                                    if (result)
1845
                                        break;
1846
                                }
1847
                            }
1848

    
1849
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1850
                            _LMLabelPresist.Commit();
1851
                            ReleaseCOMObjects(_LMLabelPresist);
1852
                        }
1853

    
1854
                        ReleaseCOMObjects(_TargetItem);
1855
                    }
1856
                }
1857
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1858
                {
1859
                    Line targetLine = targetItem as Line;
1860
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1861
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1862
                    if (connectedLMConnector != null)
1863
                    {
1864
                        // LEADER Line 검사
1865
                        bool leaderLine = false;
1866
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1867
                        if (symbolMapping != null)
1868
                            leaderLine = symbolMapping.LEADERLINE;
1869

    
1870
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1871
                        if (_LMLabelPresist != null)
1872
                        {
1873
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1874
                            _LMLabelPresist.Commit();
1875
                            ReleaseCOMObjects(_LMLabelPresist);
1876
                        }
1877
                        ReleaseCOMObjects(connectedLMConnector);
1878
                    }
1879

    
1880
                    foreach (var item in connectorVertices)
1881
                        if (item.Key != null)
1882
                            ReleaseCOMObjects(item.Key);
1883
                }
1884
            }
1885
        }
1886

    
1887
        /// <summary>
1888
        /// Equipment를 실제로 Modeling 메서드
1889
        /// </summary>
1890
        /// <param name="equipment"></param>
1891
        private void EquipmentModeling(Equipment equipment)
1892
        {
1893
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1894
                return;
1895

    
1896
            LMSymbol _LMSymbol = null;
1897
            LMSymbol targetItem = null;
1898
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1899
            double x = equipment.SPPID.ORIGINAL_X;
1900
            double y = equipment.SPPID.ORIGINAL_Y;
1901
            int mirror = 0;
1902
            double angle = equipment.ANGLE;
1903

    
1904
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1905

    
1906
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1907
            if (connector != null)
1908
            {
1909
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1910
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1911
                if (connEquipment != null)
1912
                {
1913
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1914
                        EquipmentModeling(connEquipment);
1915

    
1916
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1917
                    {
1918
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1919
                        if (targetItem != null)
1920
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1921
                        else
1922
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1923
                    }
1924
                    else
1925
                    {
1926
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1927
                    }
1928
                }
1929
                else if (connVendorPackage != null)
1930
                {
1931
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
1932
                    {
1933
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
1934
                        if (targetItem != null)
1935
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1936
                        else
1937
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1938
                    }
1939
                }
1940
                else
1941
                {
1942
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1943
                }
1944
            }
1945
            else
1946
            {
1947
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1948
            }
1949

    
1950
            if (_LMSymbol != null)
1951
            {
1952
                _LMSymbol.Commit();
1953
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1954
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1955
                ReleaseCOMObjects(_LMSymbol);
1956
            }
1957

    
1958
            if (targetItem != null)
1959
            {
1960
                ReleaseCOMObjects(targetItem);
1961
            }
1962

    
1963
            ReleaseCOMObjects(_LMSymbol);
1964
        }
1965

    
1966
        private void VendorPackageModeling(VendorPackage vendorPackage)
1967
        {
1968
            ETCSetting setting = ETCSetting.GetInstance();
1969
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
1970
            {
1971
                string symbolPath = setting.VendorPackageSymbolPath;
1972
                double x = vendorPackage.SPPID.ORIGINAL_X;
1973
                double y = vendorPackage.SPPID.ORIGINAL_Y;
1974

    
1975
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
1976
                if (symbol != null)
1977
                {
1978
                    symbol.Commit();
1979
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
1980
                }
1981

    
1982
                ReleaseCOMObjects(symbol);
1983
                symbol = null;
1984
            }
1985
        }
1986

    
1987
        /// <summary>
1988
        /// 첫 진입점
1989
        /// </summary>
1990
        /// <param name="symbol"></param>
1991
        private void SymbolModelingBySymbol(Symbol symbol)
1992
        {
1993
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1994
            List<object> endObjects = new List<object>();
1995
            endObjects.Add(symbol);
1996

    
1997
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1998
            foreach (var connector in symbol.CONNECTORS)
1999
            {
2000
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2001
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2002
                {
2003
                    endObjects.Add(connItem);
2004
                    if (connItem.GetType() == typeof(Symbol))
2005
                    {
2006
                        Symbol connSymbol = connItem as Symbol;
2007
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2008
                        {
2009
                            SymbolModeling(connSymbol, symbol);
2010
                        }
2011
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2012
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2013
                    }
2014
                    else if (connItem.GetType() == typeof(Line))
2015
                    {
2016
                        Line connLine = connItem as Line;
2017
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2018
                    }
2019
                }
2020
            }
2021
        }
2022

    
2023
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
2024
        {
2025
            foreach (var connector in symbol.CONNECTORS)
2026
            {
2027
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2028
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2029
                {
2030
                    if (!endObjects.Contains(connItem))
2031
                    {
2032
                        endObjects.Add(connItem);
2033
                        if (connItem.GetType() == typeof(Symbol))
2034
                        {
2035
                            Symbol connSymbol = connItem as Symbol;
2036
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2037
                            {
2038
                                SymbolModeling(connSymbol, symbol);
2039
                            }
2040
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2041
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2042
                        }
2043
                        else if (connItem.GetType() == typeof(Line))
2044
                        {
2045
                            Line connLine = connItem as Line;
2046
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2047
                        }
2048
                    }
2049
                }
2050
            }
2051
        }
2052

    
2053
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2054
        {
2055
            foreach (var connector in line.CONNECTORS)
2056
            {
2057
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2058
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2059
                {
2060
                    if (!endObjects.Contains(connItem))
2061
                    {
2062
                        endObjects.Add(connItem);
2063
                        if (connItem.GetType() == typeof(Symbol))
2064
                        {
2065
                            Symbol connSymbol = connItem as Symbol;
2066
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2067
                            {
2068
                                List<Symbol> group = new List<Symbol>();
2069
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2070
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2071
                                List<Symbol> endModelingGroup = new List<Symbol>();
2072
                                if (priority != null)
2073
                                {
2074
                                    SymbolGroupModeling(priority, group);
2075

    
2076
                                    // Range 겹치는지 확인해야함
2077
                                    double[] prevRange = null;
2078
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2079
                                    double[] groupRange = null;
2080
                                    GetSPPIDSymbolRange(group, ref groupRange);
2081

    
2082
                                    double distanceX = 0;
2083
                                    double distanceY = 0;
2084
                                    bool overlapX = false;
2085
                                    bool overlapY = false;
2086
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2087
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2088
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2089
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2090
                                    {
2091
                                        RemoveSymbol(group);
2092
                                        foreach (var _temp in group)
2093
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2094

    
2095
                                        SymbolGroupModeling(priority, group);
2096
                                    }
2097
                                }
2098
                                else
2099
                                {
2100
                                    SymbolModeling(connSymbol, null);
2101
                                    // Range 겹치는지 확인해야함
2102
                                    double[] prevRange = null;
2103
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2104
                                    double[] connRange = null;
2105
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
2106

    
2107
                                    double distanceX = 0;
2108
                                    double distanceY = 0;
2109
                                    bool overlapX = false;
2110
                                    bool overlapY = false;
2111
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2112
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2113
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2114
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2115
                                    {
2116
                                        RemoveSymbol(connSymbol);
2117
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2118

    
2119
                                        SymbolModeling(connSymbol, null);
2120
                                    }
2121
                                }
2122
                            }
2123
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2124
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2125
                        }
2126
                        else if (connItem.GetType() == typeof(Line))
2127
                        {
2128
                            Line connLine = connItem as Line;
2129
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2130
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2131
                        }
2132
                    }
2133
                }
2134
            }
2135
        }
2136

    
2137
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2138
        {
2139
            List<Symbol> endModelingGroup = new List<Symbol>();
2140
            SymbolModeling(firstSymbol, null);
2141
            endModelingGroup.Add(firstSymbol);
2142
            while (endModelingGroup.Count != group.Count)
2143
            {
2144
                foreach (var _symbol in group)
2145
                {
2146
                    if (!endModelingGroup.Contains(_symbol))
2147
                    {
2148
                        foreach (var _connector in _symbol.CONNECTORS)
2149
                        {
2150
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2151
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2152
                            {
2153
                                SymbolModeling(_symbol, _connSymbol);
2154
                                endModelingGroup.Add(_symbol);
2155
                                break;
2156
                            }
2157
                        }
2158
                    }
2159
                }
2160
            }
2161
        }
2162

    
2163
        /// <summary>
2164
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2165
        /// </summary>
2166
        /// <param name="childSymbol"></param>
2167
        /// <param name="parentSymbol"></param>
2168
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2169
        {
2170
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2171
            double x1 = 0;
2172
            double x2 = 0;
2173
            double y1 = 0;
2174
            double y2 = 0;
2175
            symbol2d.Range(out x1, out y1, out x2, out y2);
2176

    
2177
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2178
            if (_LMSymbol != null)
2179
            {
2180
                _LMSymbol.Commit();
2181
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2182
                foreach (var item in childSymbol.ChildSymbols)
2183
                    CreateChildSymbol(item, _LMSymbol, parent);
2184
            }
2185

    
2186

    
2187
            ReleaseCOMObjects(_LMSymbol);
2188
        }
2189
        double index = 0;
2190
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2191
        {
2192
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2193
                return;
2194

    
2195
            List<Line> group = new List<Line>();
2196
            GetConnectedLineGroup(line, group);
2197
            LineCoordinateCorrection(group);
2198

    
2199
            foreach (var groupLine in group)
2200
            {
2201
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2202
                {
2203
                    BranchLines.Add(groupLine);
2204
                    continue;
2205
                }
2206

    
2207
                bool diagonal = false;
2208
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2209
                    diagonal = true;
2210
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2211
                LMSymbol _LMSymbolStart = null;
2212
                LMSymbol _LMSymbolEnd = null;
2213
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2214
                foreach (var connector in groupLine.CONNECTORS)
2215
                {
2216
                    double x = 0;
2217
                    double y = 0;
2218
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2219
                    if (connector.ConnectedObject == null)
2220
                    {
2221
                        placeRunInputs.AddPoint(x, y);
2222
                    }
2223
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2224
                    {
2225
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2226
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2227
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2228
                        {
2229
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2230
                            if (_LMSymbolStart != null)
2231
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2232
                            else
2233
                                placeRunInputs.AddPoint(x, y);
2234
                        }
2235
                        else
2236
                        {
2237
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2238
                            if (_LMSymbolEnd != null)
2239
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2240
                            else
2241
                                placeRunInputs.AddPoint(x, y);
2242
                        }
2243
                    }
2244
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2245
                    {
2246
                        Line targetLine = connector.ConnectedObject as Line;
2247
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2248
                        {
2249
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2250
                            if (targetConnector != null)
2251
                            {
2252
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2253
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2254
                            }
2255
                            else
2256
                            {
2257
                                placeRunInputs.AddPoint( x, y);
2258
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2259
                            }
2260
                        }
2261
                        else
2262
                        {
2263
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2264
                            {
2265
                                index += 0.01;
2266
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2267
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2268
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2269
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2270
                                else
2271
                                {
2272
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2273
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2274
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2275
                                    else
2276
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2277
                                }
2278
                            }
2279

    
2280
                            placeRunInputs.AddPoint(x, y);
2281

    
2282
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2283
                            {
2284
                                index += 0.01;
2285
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2286
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2287
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2288
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2289
                                else
2290
                                {
2291
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2292
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2293
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2294
                                    else
2295
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2296
                                }
2297
                            }
2298
                        }
2299
                    }
2300
                }
2301

    
2302
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2303
                if (_lMConnector != null)
2304
                {
2305
                    _lMConnector.Commit();
2306
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2307

    
2308
                    bool bRemodelingStart = false;
2309
                    if (_LMSymbolStart != null)
2310
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2311
                    bool bRemodelingEnd = false;
2312
                    if (_LMSymbolEnd != null)
2313
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2314

    
2315
                    if (bRemodelingStart || bRemodelingEnd)
2316
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2317

    
2318
                    FlowMarkModeling(groupLine);
2319
                    LineNumberModelingOnlyOne(groupLine);
2320

    
2321
                    ReleaseCOMObjects(_lMConnector);
2322
                }
2323
                else if (!isBranchModeling)
2324
                {
2325
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2326
                }
2327

    
2328
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2329
                x.ConnectedObject != null &&
2330
                x.ConnectedObject.GetType() == typeof(Line) &&
2331
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2332
                .Select(x => x.ConnectedObject)
2333
                .ToList();
2334

    
2335
                foreach (var item in removeLines)
2336
                    RemoveLineForModeling(item as Line);
2337

    
2338
                if (_LMAItem != null)
2339
                    ReleaseCOMObjects(_LMAItem);
2340
                if (placeRunInputs != null)
2341
                    ReleaseCOMObjects(placeRunInputs);
2342
                if (_LMSymbolStart != null)
2343
                    ReleaseCOMObjects(_LMSymbolStart);
2344
                if (_LMSymbolEnd != null)
2345
                    ReleaseCOMObjects(_LMSymbolEnd);
2346

    
2347
                if (isBranchModeling && BranchLines.Contains(groupLine))
2348
                    BranchLines.Remove(groupLine);
2349
            }
2350
        }
2351

    
2352
        private void RemoveLineForModeling(Line line)
2353
        {
2354
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2355
            if (modelItem != null)
2356
            {
2357
                foreach (LMRepresentation rep in modelItem.Representations)
2358
                {
2359
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2360
                    {
2361
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2362
                        dynamic OID = rep.get_GraphicOID().ToString();
2363
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2364
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2365
                        int verticesCount = lineStringGeometry.VertexCount;
2366
                        double[] vertices = null;
2367
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2368
                        for (int i = 0; i < verticesCount; i++)
2369
                        {
2370
                            double x = 0;
2371
                            double y = 0;
2372
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2373
                            if (verticesCount == 2 && (x < 0 || y < 0))
2374
                                _placement.PIDRemovePlacement(rep);
2375
                        }
2376
                        ReleaseCOMObjects(_LMConnector);
2377
                    }
2378
                }
2379

    
2380
                ReleaseCOMObjects(modelItem);
2381
            }
2382
        }
2383

    
2384
        private void GetConnectedLineGroup(Line line, List<Line> group)
2385
        {
2386
            if (!group.Contains(line))
2387
                group.Add(line);
2388
            foreach (var connector in line.CONNECTORS)
2389
            {
2390
                if (connector.ConnectedObject != null &&
2391
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2392
                    !group.Contains(connector.ConnectedObject) &&
2393
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2394
                {
2395
                    Line connLine = connector.ConnectedObject as Line;
2396
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2397
                    {
2398
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2399
                            group.Insert(0, connLine);
2400
                        else
2401
                            group.Add(connLine);
2402
                        GetConnectedLineGroup(connLine, group);
2403
                    }
2404
                }
2405
            }
2406
        }
2407

    
2408
        private void LineCoordinateCorrection(List<Line> group)
2409
        {
2410
            // 순서대로 전 Item 기준 정렬
2411
            LineCoordinateCorrectionByStart(group);
2412

    
2413
            // 역으로 심볼이 있을 경우 좌표 보정
2414
            LineCoordinateCorrectionForLastLine(group);
2415
        }
2416

    
2417
        private void LineCoordinateCorrectionByStart(List<Line> group)
2418
        {
2419
            for (int i = 0; i < group.Count; i++)
2420
            {
2421
                Line line = group[i];
2422
                if (i == 0)
2423
                {
2424
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2425
                    if (symbolConnector != null)
2426
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2427
                }
2428
                else if (i != 0)
2429
                {
2430
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2431
                }
2432
            }
2433
        }
2434

    
2435
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2436
        {
2437
            Line checkLine = group[group.Count - 1];
2438
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2439
            if (lastSymbolConnector != null)
2440
            {
2441
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2442
                for (int i = group.Count - 2; i >= 0; i--)
2443
                {
2444
                    Line line = group[i + 1];
2445
                    Line prevLine = group[i];
2446

    
2447
                    // 같으면 보정
2448
                    if (line.SlopeType == prevLine.SlopeType)
2449
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2450
                    else
2451
                    {
2452
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2453
                        {
2454
                            double prevX = 0;
2455
                            double prevY = 0;
2456
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2457
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2458

    
2459
                            double x = 0;
2460
                            double y = 0;
2461
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2462
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2463
                        }
2464
                        else if (line.SlopeType == SlopeType.VERTICAL)
2465
                        {
2466
                            double prevX = 0;
2467
                            double prevY = 0;
2468
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2469
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2470

    
2471
                            double x = 0;
2472
                            double y = 0;
2473
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2474
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2475
                        }
2476
                        break;
2477
                    }
2478
                }
2479
            }
2480
        }
2481

    
2482
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2483
        {
2484
            double x = 0;
2485
            double y = 0;
2486
            if (connItem.GetType() == typeof(Symbol))
2487
            {
2488
                Symbol targetSymbol = connItem as Symbol;
2489
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2490
                if (targetConnector != null)
2491
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2492
                else
2493
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2494
            }
2495
            else if (connItem.GetType() == typeof(Line))
2496
            {
2497
                Line targetLine = connItem as Line;
2498
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2499
            }
2500

    
2501
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2502
        }
2503

    
2504
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2505
        {
2506
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2507
            int index = line.CONNECTORS.IndexOf(connector);
2508
            if (index == 0)
2509
            {
2510
                line.SPPID.START_X = x;
2511
                line.SPPID.START_Y = y;
2512
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2513
                    line.SPPID.END_Y = y;
2514
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2515
                    line.SPPID.END_X = x;
2516
            }
2517
            else
2518
            {
2519
                line.SPPID.END_X = x;
2520
                line.SPPID.END_Y = y;
2521
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2522
                    line.SPPID.START_Y = y;
2523
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2524
                    line.SPPID.START_X = x;
2525
            }
2526
        }
2527

    
2528
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2529
        {
2530
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2531
            int index = line.CONNECTORS.IndexOf(connector);
2532
            if (index == 0)
2533
            {
2534
                line.SPPID.START_X = x;
2535
                if (line.SlopeType == SlopeType.VERTICAL)
2536
                    line.SPPID.END_X = x;
2537
            }
2538
            else
2539
            {
2540
                line.SPPID.END_X = x;
2541
                if (line.SlopeType == SlopeType.VERTICAL)
2542
                    line.SPPID.START_X = x;
2543
            }
2544
        }
2545

    
2546
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2547
        {
2548
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2549
            int index = line.CONNECTORS.IndexOf(connector);
2550
            if (index == 0)
2551
            {
2552
                line.SPPID.START_Y = y;
2553
                if (line.SlopeType == SlopeType.HORIZONTAL)
2554
                    line.SPPID.END_Y = y;
2555
            }
2556
            else
2557
            {
2558
                line.SPPID.END_Y = y;
2559
                if (line.SlopeType == SlopeType.HORIZONTAL)
2560
                    line.SPPID.START_Y = y;
2561
            }
2562
        }
2563

    
2564
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2565
        {
2566
            if (symbol != null)
2567
            {
2568
                string repID = symbol.AsLMRepresentation().Id;
2569
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2570
                string lineUID = line.UID;
2571

    
2572
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2573
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2574
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2575

    
2576
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2577
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2578
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2579

    
2580
                if (startSpecBreak != null || startEndBreak != null)
2581
                    result = true;
2582
            }
2583
        }
2584

    
2585
        /// <summary>
2586
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2587
        /// </summary>
2588
        /// <param name="lines"></param>
2589
        /// <param name="prevLMConnector"></param>
2590
        /// <param name="startSymbol"></param>
2591
        /// <param name="endSymbol"></param>
2592
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2593
        {
2594
            string symbolPath = string.Empty;
2595
            #region get symbol path
2596
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2597
            symbolPath = GetSPPIDFileName(modelItem);
2598
            ReleaseCOMObjects(modelItem);
2599
            #endregion
2600
            bool diagonal = false;
2601
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2602
                diagonal = true;
2603
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2604
            LMConnector newConnector = null;
2605
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2606
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2607
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2608
            int verticesCount = lineStringGeometry.VertexCount;
2609
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2610

    
2611
            List<double[]> vertices = new List<double[]>();
2612
            for (int i = 1; i <= verticesCount; i++)
2613
            {
2614
                double x = 0;
2615
                double y = 0;
2616
                lineStringGeometry.GetVertex(i, ref x, ref y);
2617
                vertices.Add(new double[] { x, y });
2618
            }
2619

    
2620
            for (int i = 0; i < vertices.Count; i++)
2621
            {
2622
                double[] points = vertices[i];
2623
                // 시작 심볼이 있고 첫번째 좌표일 때
2624
                if (startSymbol != null && i == 0)
2625
                {
2626
                    if (bStart)
2627
                    {
2628
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2629
                        if (slopeType == SlopeType.HORIZONTAL)
2630
                            placeRunInputs.AddPoint(points[0], -0.1);
2631
                        else if (slopeType == SlopeType.VERTICAL)
2632
                            placeRunInputs.AddPoint(-0.1, points[1]);
2633
                        else
2634
                            placeRunInputs.AddPoint(points[0], -0.1);
2635

    
2636
                        placeRunInputs.AddPoint(points[0], points[1]);
2637
                    }
2638
                    else
2639
                    {
2640
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2641
                    }
2642
                }
2643
                // 마지막 심볼이 있고 마지막 좌표일 때
2644
                else if (endSymbol != null && i == vertices.Count - 1)
2645
                {
2646
                    if (bEnd)
2647
                    {
2648
                        placeRunInputs.AddPoint(points[0], points[1]);
2649

    
2650
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2651
                        if (slopeType == SlopeType.HORIZONTAL)
2652
                            placeRunInputs.AddPoint(points[0], -0.1);
2653
                        else if (slopeType == SlopeType.VERTICAL)
2654
                            placeRunInputs.AddPoint(-0.1, points[1]);
2655
                        else
2656
                            placeRunInputs.AddPoint(points[0], -0.1);
2657
                    }
2658
                    else
2659
                    {
2660
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2661
                    }
2662
                }
2663
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2664
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2665
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2666
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2667
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2668
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2669
                else
2670
                    placeRunInputs.AddPoint(points[0], points[1]);
2671
            }
2672

    
2673
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2674
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2675

    
2676
            ReleaseCOMObjects(placeRunInputs);
2677
            ReleaseCOMObjects(_LMAItem);
2678
            ReleaseCOMObjects(modelItem);
2679

    
2680
            if (newConnector != null)
2681
            {
2682
                newConnector.Commit();
2683
                if (startSymbol != null && bStart)
2684
                {
2685
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2686
                    placeRunInputs = new PlaceRunInputs();
2687
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2688
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2689
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2690
                    if (_LMConnector != null)
2691
                    {
2692
                        _LMConnector.Commit();
2693
                        RemoveConnectorForReModelingLine(newConnector);
2694
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2695
                        ReleaseCOMObjects(_LMConnector);
2696
                    }
2697
                    ReleaseCOMObjects(placeRunInputs);
2698
                    ReleaseCOMObjects(_LMAItem);
2699
                }
2700

    
2701
                if (endSymbol != null && bEnd)
2702
                {
2703
                    if (startSymbol != null)
2704
                    {
2705
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2706
                        newConnector = dicVertices.First().Key;
2707
                    }
2708

    
2709
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2710
                    placeRunInputs = new PlaceRunInputs();
2711
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2712
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2713
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2714
                    if (_LMConnector != null)
2715
                    {
2716
                        _LMConnector.Commit();
2717
                        RemoveConnectorForReModelingLine(newConnector);
2718
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2719
                        ReleaseCOMObjects(_LMConnector);
2720
                    }
2721
                    ReleaseCOMObjects(placeRunInputs);
2722
                    ReleaseCOMObjects(_LMAItem);
2723
                }
2724

    
2725
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2726
                ReleaseCOMObjects(newConnector);
2727
            }
2728

    
2729
            ReleaseCOMObjects(modelItem);
2730
        }
2731

    
2732
        /// <summary>
2733
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2734
        /// </summary>
2735
        /// <param name="connector"></param>
2736
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2737
        {
2738
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2739
            foreach (var item in dicVertices)
2740
            {
2741
                if (item.Value.Count == 2)
2742
                {
2743
                    bool result = false;
2744
                    foreach (var point in item.Value)
2745
                    {
2746
                        if (point[0] < 0 || point[1] < 0)
2747
                        {
2748
                            result = true;
2749
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2750
                            break;
2751
                        }
2752
                    }
2753

    
2754
                    if (result)
2755
                        break;
2756
                }
2757
            }
2758
            foreach (var item in dicVertices)
2759
                ReleaseCOMObjects(item.Key);
2760
        }
2761

    
2762
        /// <summary>
2763
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2764
        /// </summary>
2765
        /// <param name="symbol"></param>
2766
        /// <param name="line"></param>
2767
        /// <returns></returns>
2768
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2769
        {
2770
            LMSymbol _LMSymbol = null;
2771
            foreach (var connector in symbol.CONNECTORS)
2772
            {
2773
                if (connector.CONNECTEDITEM == line.UID)
2774
                {
2775
                    if (connector.Index == 0)
2776
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2777
                    else
2778
                    {
2779
                        ChildSymbol child = null;
2780
                        foreach (var childSymbol in symbol.ChildSymbols)
2781
                        {
2782
                            if (childSymbol.Connectors.Contains(connector))
2783
                                child = childSymbol;
2784
                            else
2785
                                child = GetChildSymbolByConnector(childSymbol, connector);
2786

    
2787
                            if (child != null)
2788
                                break;
2789
                        }
2790

    
2791
                        if (child != null)
2792
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2793
                    }
2794

    
2795
                    break;
2796
                }
2797
            }
2798

    
2799
            return _LMSymbol;
2800
        }
2801

    
2802
        /// <summary>
2803
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2804
        /// </summary>
2805
        /// <param name="item"></param>
2806
        /// <param name="connector"></param>
2807
        /// <returns></returns>
2808
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2809
        {
2810
            foreach (var childSymbol in item.ChildSymbols)
2811
            {
2812
                if (childSymbol.Connectors.Contains(connector))
2813
                    return childSymbol;
2814
                else
2815
                    return GetChildSymbolByConnector(childSymbol, connector);
2816
            }
2817

    
2818
            return null;
2819
        }
2820

    
2821
        /// <summary>
2822
        /// EndBreak 모델링 메서드
2823
        /// </summary>
2824
        /// <param name="endBreak"></param>
2825
        private void EndBreakModeling(EndBreak endBreak)
2826
        {
2827
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2828
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2829

    
2830
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2831
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
2832
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2833

    
2834
            if (targetLMConnector != null)
2835
            {
2836
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2837
                Array array = null;
2838
                if (point != null)
2839
                    array = new double[] { 0, point[0], point[1] };
2840
                else
2841
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2842
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2843
                if (_LmLabelPersist != null)
2844
                {
2845
                    _LmLabelPersist.Commit();
2846
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2847
                    if (_LmLabelPersist.ModelItemObject != null)
2848
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2849
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2850
                    ReleaseCOMObjects(_LmLabelPersist);
2851
                }
2852
                ReleaseCOMObjects(targetLMConnector);
2853
            }
2854
            else
2855
            {
2856
                Log.Write("End Break UID : " + endBreak.UID);
2857
                Log.Write("Can't find targetLMConnector");
2858
            }
2859
        }
2860

    
2861
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
2862
        {
2863
            string symbolPath = string.Empty;
2864
            #region get symbol path
2865
            if (string.IsNullOrEmpty(changeSymbolPath))
2866
            {
2867
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2868
                symbolPath = GetSPPIDFileName(modelItem);
2869
                ReleaseCOMObjects(modelItem);
2870
            }
2871
            else
2872
                symbolPath = changeSymbolPath;
2873
            
2874
            #endregion
2875

    
2876
            LMConnector newConnector = null;
2877
            dynamic OID = connector.get_GraphicOID().ToString();
2878
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2879
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2880
            int verticesCount = lineStringGeometry.VertexCount;
2881
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2882
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2883

    
2884
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2885
            {
2886
                double[] vertices = null;
2887
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2888
                double x = 0;
2889
                double y = 0;
2890
                lineStringGeometry.GetVertex(1, ref x, ref y);
2891

    
2892
                string flowDirection = string.Empty;
2893
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2894
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2895
                    flowDirection = flowAttribute.get_Value().ToString();
2896

    
2897
                if (flowDirection == "End 1 is downstream (Outlet)")
2898
                {
2899
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2900
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2901
                    flowDirection = "End 1 is upstream (Inlet)";
2902
                }
2903
                else
2904
                {
2905
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2906
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2907
                }
2908
                string oldModelItemId = connector.ModelItemID;
2909
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2910
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2911
                newConnector.Commit();
2912
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2913
                if (!string.IsNullOrEmpty(flowDirection))
2914
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2915
                ReleaseCOMObjects(connector);
2916

    
2917
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
2918
                {
2919
                    foreach (var repId in line.SPPID.Representations)
2920
                    {
2921
                        LMConnector _connector = dataSource.GetConnector(repId);
2922
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
2923
                        {
2924
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
2925
                            {
2926
                                line.SPPID.ModelItemId = _connector.ModelItemID;
2927
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
2928
                            }
2929
                        }
2930
                        ReleaseCOMObjects(_connector);
2931
                        _connector = null;
2932
                    }
2933
                }
2934
            }
2935

    
2936
            return newConnector;
2937
        }
2938

    
2939
        /// <summary>
2940
        /// SpecBreak Modeling 메서드
2941
        /// </summary>
2942
        /// <param name="specBreak"></param>
2943
        private void SpecBreakModeling(SpecBreak specBreak)
2944
        {
2945
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2946
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2947

    
2948
            if (upStreamObj != null &&
2949
                downStreamObj != null)
2950
            {
2951
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2952
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && targetLMConnector != null)
2953
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2954

    
2955
                if (targetLMConnector != null)
2956
                {
2957
                    foreach (var attribute in specBreak.ATTRIBUTES)
2958
                    {
2959
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2960
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2961
                        {
2962
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2963
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2964
                            Array array = null;
2965
                            if (point != null)
2966
                                array = new double[] { 0, point[0], point[1] };
2967
                            else
2968
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2969
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2970

    
2971
                            if (_LmLabelPersist != null)
2972
                            {
2973
                                _LmLabelPersist.Commit();
2974
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2975
                                if (_LmLabelPersist.ModelItemObject != null)
2976
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2977
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2978
                                ReleaseCOMObjects(_LmLabelPersist);
2979
                            }
2980
                        }
2981
                    }
2982
                    ReleaseCOMObjects(targetLMConnector);
2983
                }
2984
                else
2985
                {
2986
                    Log.Write("Spec Break UID : " + specBreak.UID);
2987
                    Log.Write("Can't find targetLMConnector");
2988
                }
2989
            }
2990
        }
2991

    
2992
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2993
        {
2994
            LMConnector targetConnector = null;
2995
            Symbol targetSymbol = targetObj as Symbol;
2996
            Symbol connectedSymbol = connectedObj as Symbol;
2997
            Line targetLine = targetObj as Line;
2998
            Line connectedLine = connectedObj as Line;
2999
            if (targetSymbol != null && connectedSymbol != null)
3000
            {
3001
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3002
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3003

    
3004
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3005
                {
3006
                    if (connector.get_ItemStatus() != "Active")
3007
                        continue;
3008

    
3009
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3010
                    {
3011
                        targetConnector = connector;
3012
                        break;
3013
                    }
3014
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3015
                    {
3016
                        targetConnector = connector;
3017
                        break;
3018
                    }
3019
                }
3020

    
3021
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3022
                {
3023
                    if (connector.get_ItemStatus() != "Active")
3024
                        continue;
3025

    
3026
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3027
                    {
3028
                        targetConnector = connector;
3029
                        break;
3030
                    }
3031
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3032
                    {
3033
                        targetConnector = connector;
3034
                        break;
3035
                    }
3036
                }
3037

    
3038
                ReleaseCOMObjects(targetLMSymbol);
3039
                ReleaseCOMObjects(connectedLMSymbol);
3040
            }
3041
            else if (targetLine != null && connectedLine != null)
3042
            {
3043
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3044
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3045

    
3046
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3047
                {
3048
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3049
                    {
3050
                        if (targetConnector != null)
3051
                            break;
3052

    
3053
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3054
                        {
3055
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3056

    
3057
                            if (IsConnected(_LMConnector, connectedModelItem))
3058
                                targetConnector = _LMConnector;
3059
                            else
3060
                                ReleaseCOMObjects(_LMConnector);
3061
                        }
3062
                    }
3063

    
3064
                    ReleaseCOMObjects(targetModelItem);
3065
                }
3066
            }
3067
            else
3068
            {
3069
                LMSymbol connectedLMSymbol = null;
3070
                if (connectedSymbol != null)
3071
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3072
                else if (targetSymbol != null)
3073
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3074
                else
3075
                {
3076

    
3077
                }
3078
                LMModelItem targetModelItem = null;
3079
                if (targetLine != null)
3080
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3081
                else if (connectedLine != null)
3082
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3083
                else
3084
                {
3085

    
3086
                }
3087
                if (connectedLMSymbol != null && targetModelItem != null)
3088
                {
3089
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3090
                    {
3091
                        if (connector.get_ItemStatus() != "Active")
3092
                            continue;
3093

    
3094
                        if (IsConnected(connector, targetModelItem))
3095
                        {
3096
                            targetConnector = connector;
3097
                            break;
3098
                        }
3099
                    }
3100

    
3101
                    if (targetConnector == null)
3102
                    {
3103
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3104
                        {
3105
                            if (connector.get_ItemStatus() != "Active")
3106
                                continue;
3107

    
3108
                            if (IsConnected(connector, targetModelItem))
3109
                            {
3110
                                targetConnector = connector;
3111
                                break;
3112
                            }
3113
                        }
3114
                    }
3115
                }
3116

    
3117
            }
3118

    
3119
            return targetConnector;
3120
        }
3121

    
3122
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
3123
        {
3124
            double[] result = null;
3125
            Line targetLine = targetObj as Line;
3126
            Symbol targetSymbol = targetObj as Symbol;
3127
            Line connLine = connObj as Line;
3128
            Symbol connSymbol = connObj as Symbol;
3129

    
3130
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
3131
            double lineMove = GridSetting.GetInstance().Length * 3;
3132
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3133
            {
3134
                result = GetConnectorVertices(targetConnector)[0];
3135
                if (targetSymbol != null && connSymbol != null)
3136
                {
3137
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3138
                    if (slopeType == SlopeType.HORIZONTAL)
3139
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3140
                    else if (slopeType == SlopeType.VERTICAL)
3141
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3142
                }
3143
                else if (targetLine != null)
3144
                {
3145
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3146
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3147
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3148
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3149
                }
3150
                else if (connLine != null)
3151
                {
3152
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3153
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3154
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3155
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3156
                }
3157
            }
3158
            else
3159
            {
3160
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3161
                {
3162
                    Line line = connObj as Line;
3163
                    LMConnector connectedConnector = null;
3164
                    int connIndex = 0;
3165
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3166
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3167

    
3168
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3169

    
3170
                    ReleaseCOMObjects(modelItem);
3171
                    ReleaseCOMObjects(connectedConnector);
3172

    
3173
                    if (vertices.Count > 0)
3174
                    {
3175
                        if (connIndex == 1)
3176
                            result = vertices[0];
3177
                        else if (connIndex == 2)
3178
                            result = vertices[vertices.Count - 1];
3179

    
3180
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3181
                        {
3182
                            result = new double[] { result[0], result[1] - lineMove };
3183
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3184
                            {
3185
                                result = new double[] { result[0] - lineMove, result[1] };
3186
                            }
3187
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3188
                            {
3189
                                result = new double[] { result[0] + lineMove, result[1] };
3190
                            }
3191
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3192
                            {
3193
                                result = new double[] { result[0] + lineMove, result[1] };
3194
                            }
3195
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3196
                            {
3197
                                result = new double[] { result[0] - lineMove, result[1] };
3198
                            }
3199
                        }
3200
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3201
                        {
3202
                            result = new double[] { result[0] - lineMove, result[1] };
3203
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3204
                            {
3205
                                result = new double[] { result[0], result[1] - lineMove };
3206
                            }
3207
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3208
                            {
3209
                                result = new double[] { result[0], result[1] + lineMove };
3210
                            }
3211
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3212
                            {
3213
                                result = new double[] { result[0], result[1] + lineMove };
3214
                            }
3215
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3216
                            {
3217
                                result = new double[] { result[0], result[1] - lineMove };
3218
                            }
3219
                        }
3220
                            
3221
                    }
3222
                }
3223
                else
3224
                {
3225
                    Log.Write("error in GetSegemtPoint");
3226
                }
3227
            }
3228

    
3229
            return result;
3230
        }
3231

    
3232
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3233
        {
3234
            bool result = false;
3235

    
3236
            foreach (LMRepresentation rep in modelItem.Representations)
3237
            {
3238
                if (result)
3239
                    break;
3240

    
3241
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3242
                {
3243
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3244

    
3245
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3246
                        connector.ConnectItem1SymbolObject != null &&
3247
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3248
                    {
3249
                        result = true;
3250
                        ReleaseCOMObjects(_LMConnector);
3251
                        break;
3252
                    }
3253
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3254
                        connector.ConnectItem2SymbolObject != null &&
3255
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3256
                    {
3257
                        result = true;
3258
                        ReleaseCOMObjects(_LMConnector);
3259
                        break;
3260
                    }
3261
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3262
                        connector.ConnectItem1SymbolObject != null &&
3263
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3264
                    {
3265
                        result = true;
3266
                        ReleaseCOMObjects(_LMConnector);
3267
                        break;
3268
                    }
3269
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3270
                        connector.ConnectItem2SymbolObject != null &&
3271
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3272
                    {
3273
                        result = true;
3274
                        ReleaseCOMObjects(_LMConnector);
3275
                        break;
3276
                    }
3277

    
3278
                    ReleaseCOMObjects(_LMConnector);
3279
                }
3280
            }
3281

    
3282

    
3283
            return result;
3284
        }
3285

    
3286
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3287
        {
3288
            foreach (LMRepresentation rep in modelItem.Representations)
3289
            {
3290
                if (connectedConnector != null)
3291
                    break;
3292

    
3293
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3294
                {
3295
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3296

    
3297
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3298
                        connector.ConnectItem1SymbolObject != null &&
3299
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3300
                    {
3301
                        connectedConnector = _LMConnector;
3302
                        connectorIndex = 1;
3303
                        break;
3304
                    }
3305
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3306
                        connector.ConnectItem2SymbolObject != null &&
3307
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3308
                    {
3309
                        connectedConnector = _LMConnector;
3310
                        connectorIndex = 2;
3311
                        break;
3312
                    }
3313
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3314
                        connector.ConnectItem1SymbolObject != null &&
3315
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3316
                    {
3317
                        connectedConnector = _LMConnector;
3318
                        connectorIndex = 1;
3319
                        break;
3320
                    }
3321
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3322
                        connector.ConnectItem2SymbolObject != null &&
3323
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3324
                    {
3325
                        connectedConnector = _LMConnector;
3326
                        connectorIndex = 2;
3327
                        break;
3328
                    }
3329

    
3330
                    if (connectedConnector == null)
3331
                        ReleaseCOMObjects(_LMConnector);
3332
                }
3333
            }
3334
        }
3335

    
3336
        /// <summary>
3337
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3338
        /// </summary>
3339
        /// <param name="modelItemID1"></param>
3340
        /// <param name="modelItemID2"></param>
3341
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
3342
        {
3343
            try
3344
            {
3345
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3346
                _LMAItem item1 = modelItem1.AsLMAItem();
3347
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3348
                _LMAItem item2 = modelItem2.AsLMAItem();
3349

    
3350
                // item2가 item1으로 조인
3351
                _placement.PIDJoinRuns(ref item1, ref item2);
3352
                item1.Commit();
3353
                item2.Commit();
3354

    
3355
                string beforeID = string.Empty;
3356
                string afterID = string.Empty;
3357

    
3358
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3359
                {
3360
                    beforeID = modelItem2.Id;
3361
                    afterID = modelItem1.Id;
3362
                    survivorId = afterID;
3363
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
3364
                    if (attribute != null)
3365
                        attribute.set_Value("End 1 is upstream (Inlet)");
3366
                }
3367
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3368
                {
3369
                    beforeID = modelItem1.Id;
3370
                    afterID = modelItem2.Id;
3371
                    survivorId = afterID;
3372
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
3373
                    if (attribute != null)
3374
                        attribute.set_Value("End 1 is upstream (Inlet)");
3375
                }
3376
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3377
                {
3378
                    int model1Cnt = GetConnectorCount(modelId1);
3379
                    int model2Cnt = GetConnectorCount(modelId2);
3380
                    if (model1Cnt == 0)
3381
                    {
3382
                        beforeID = modelItem1.Id;
3383
                        afterID = modelItem2.Id;
3384
                        survivorId = afterID;
3385
                        LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
3386
                        if (attribute != null)
3387
                            attribute.set_Value("End 1 is upstream (Inlet)");
3388
                    }
3389
                    else if (model2Cnt == 0)
3390
                    {
3391
                        beforeID = modelItem2.Id;
3392
                        afterID = modelItem1.Id;
3393
                        survivorId = afterID;
3394
                        LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
3395
                        if (attribute != null)
3396
                            attribute.set_Value("End 1 is upstream (Inlet)");
3397
                    }
3398
                    else
3399
                        survivorId = null;
3400
                }
3401
                else
3402
                {
3403
                    Log.Write("잘못된 경우");
3404
                    survivorId = null;
3405
                }
3406

    
3407
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3408
                {
3409
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3410
                    foreach (var line in lines)
3411
                        line.SPPID.ModelItemId = afterID;
3412
                }
3413

    
3414
                ReleaseCOMObjects(modelItem1);
3415
                ReleaseCOMObjects(item1);
3416
                ReleaseCOMObjects(modelItem2);
3417
                ReleaseCOMObjects(item2);
3418
            }
3419
            catch (Exception ex)
3420
            {
3421
                Log.Write("Join Error");
3422
                Log.Write(ex.Message);
3423
            }
3424
        }
3425

    
3426
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3427
        {
3428
            List<string> temp = new List<string>();
3429
            List<LMConnector> connectors = new List<LMConnector>();
3430
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3431
            {
3432
                if (connector.get_ItemStatus() != "Active")
3433
                    continue;
3434

    
3435
                LMModelItem modelItem = connector.ModelItemObject;
3436
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3437
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3438
                    temp.Add(modelItem.Id);
3439

    
3440
                if (temp.Contains(modelItem.Id) &&
3441
                    connOtherSymbol != null &&
3442
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3443
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3444
                    temp.Remove(modelItem.Id);
3445

    
3446

    
3447
                if (temp.Contains(modelItem.Id))
3448
                    connectors.Add(connector);
3449
                ReleaseCOMObjects(connOtherSymbol);
3450
                connOtherSymbol = null;
3451
                ReleaseCOMObjects(modelItem);
3452
                modelItem = null;
3453
            }
3454

    
3455
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3456
            {
3457
                if (connector.get_ItemStatus() != "Active")
3458
                    continue;
3459

    
3460
                LMModelItem modelItem = connector.ModelItemObject;
3461
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3462
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3463
                    temp.Add(modelItem.Id);
3464

    
3465
                if (temp.Contains(modelItem.Id) &&
3466
                    connOtherSymbol != null &&
3467
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3468
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3469
                    temp.Remove(modelItem.Id);
3470

    
3471
                if (temp.Contains(modelItem.Id))
3472
                    connectors.Add(connector);
3473
                ReleaseCOMObjects(connOtherSymbol);
3474
                connOtherSymbol = null;
3475
                ReleaseCOMObjects(modelItem);
3476
                modelItem = null;
3477
            }
3478

    
3479

    
3480
            List<string> result = new List<string>();
3481
            string originalName = GetSPPIDFileName(modelId);
3482
            foreach (var connector in connectors)
3483
            {
3484
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3485
                if (originalName == fileName)
3486
                    result.Add(connector.ModelItemID);
3487
                else
3488
                {
3489
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3490
                        result.Add(connector.ModelItemID);
3491
                    else
3492
                    {
3493
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3494
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3495
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3496
                            result.Add(connector.ModelItemID);
3497
                    }
3498
                }
3499
            }
3500

    
3501
            foreach (var connector in connectors)
3502
                ReleaseCOMObjects(connector);
3503
            
3504
            return result;
3505

    
3506

    
3507
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3508
            {
3509
                LMSymbol findResult = null;
3510
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3511
                    findResult = connector.ConnectItem1SymbolObject;
3512
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3513
                    findResult = connector.ConnectItem2SymbolObject;
3514

    
3515
                return findResult;
3516
            }
3517
        }
3518

    
3519
        /// <summary>
3520
        /// PipeRun의 좌표를 가져오는 메서드
3521
        /// </summary>
3522
        /// <param name="modelId"></param>
3523
        /// <returns></returns>
3524
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3525
        {
3526
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3527
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3528

    
3529
            if (modelItem != null)
3530
            {
3531
                foreach (LMRepresentation rep in modelItem.Representations)
3532
                {
3533
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3534
                    {
3535
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3536
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3537
                        {
3538
                            ReleaseCOMObjects(_LMConnector);
3539
                            _LMConnector = null;
3540
                            continue;
3541
                        }
3542
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3543
                        dynamic OID = rep.get_GraphicOID().ToString();
3544
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3545
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3546
                        int verticesCount = lineStringGeometry.VertexCount;
3547
                        double[] vertices = null;
3548
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3549
                        for (int i = 0; i < verticesCount; i++)
3550
                        {
3551
                            double x = 0;
3552
                            double y = 0;
3553
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3554
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3555
                        }
3556
                    }
3557
                }
3558

    
3559
                ReleaseCOMObjects(modelItem);
3560
            }
3561

    
3562
            return connectorVertices;
3563
        }
3564

    
3565
        private List<double[]> GetConnectorVertices(LMConnector connector)
3566
        {
3567
            List<double[]> vertices = new List<double[]>();
3568
            if (connector != null)
3569
            {
3570
                dynamic OID = connector.get_GraphicOID().ToString();
3571
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3572
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3573
                int verticesCount = lineStringGeometry.VertexCount;
3574
                double[] value = null;
3575
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3576
                for (int i = 0; i < verticesCount; i++)
3577
                {
3578
                    double x = 0;
3579
                    double y = 0;
3580
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3581
                    vertices.Add(new double[] { x, y });
3582
                }
3583
            }
3584
            return vertices;
3585
        }
3586

    
3587
        /// <summary>
3588
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3589
        /// </summary>
3590
        /// <param name="connectorVertices"></param>
3591
        /// <param name="connX"></param>
3592
        /// <param name="connY"></param>
3593
        /// <returns></returns>
3594
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3595
        {
3596
            double length = double.MaxValue;
3597
            LMConnector targetConnector = null;
3598
            foreach (var item in connectorVertices)
3599
            {
3600
                List<double[]> points = item.Value;
3601
                for (int i = 0; i < points.Count - 1; i++)
3602
                {
3603
                    double[] point1 = points[i];
3604
                    double[] point2 = points[i + 1];
3605
                    double x1 = Math.Min(point1[0], point2[0]);
3606
                    double y1 = Math.Min(point1[1], point2[1]);
3607
                    double x2 = Math.Max(point1[0], point2[0]);
3608
                    double y2 = Math.Max(point1[1], point2[1]);
3609

    
3610
                    if ((x1 <= connX && x2 >= connX) ||
3611
                        (y1 <= connY && y2 >= connY))
3612
                    {
3613
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3614
                        if (length >= distance)
3615
                        {
3616
                            targetConnector = item.Key;
3617
                            length = distance;
3618
                        }
3619

    
3620
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3621
                        if (length >= distance)
3622
                        {
3623
                            targetConnector = item.Key;
3624
                            length = distance;
3625
                        }
3626
                    }
3627
                }
3628
            }
3629

    
3630
            // 못찾았을때.
3631
            length = double.MaxValue;
3632
            if (targetConnector == null)
3633
            {
3634
                foreach (var item in connectorVertices)
3635
                {
3636
                    List<double[]> points = item.Value;
3637

    
3638
                    foreach (double[] point in points)
3639
                    {
3640
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3641
                        if (length >= distance)
3642
                        {
3643
                            targetConnector = item.Key;
3644
                            length = distance;
3645
                        }
3646
                    }
3647
                }
3648
            }
3649

    
3650
            return targetConnector;
3651
        }
3652

    
3653
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3654
        {
3655
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3656
            if (vertices.Count == 0)
3657
                return null;
3658

    
3659
            double length = double.MaxValue;
3660
            LMConnector targetConnector = null;
3661
            double[] resultPoint = null;
3662
            List<double[]> targetVertices = null;
3663

    
3664
            // Vertices 포인트에 제일 가까운곳
3665
            foreach (var item in vertices)
3666
            {
3667
                List<double[]> points = item.Value;
3668
                for (int i = 0; i < points.Count; i++)
3669
                {
3670
                    double[] point = points[i];
3671
                    double tempX = point[0];
3672
                    double tempY = point[1];
3673

    
3674
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3675
                    if (length >= distance)
3676
                    {
3677
                        targetConnector = item.Key;
3678
                        length = distance;
3679
                        resultPoint = point;
3680
                        targetVertices = item.Value;
3681
                    }
3682
                }
3683
            }
3684

    
3685
            // Vertices Cross에 제일 가까운곳
3686
            foreach (var item in vertices)
3687
            {
3688
                List<double[]> points = item.Value;
3689
                for (int i = 0; i < points.Count - 1; i++)
3690
                {
3691
                    double[] point1 = points[i];
3692
                    double[] point2 = points[i + 1];
3693

    
3694
                    double maxLineX = Math.Max(point1[0], point2[0]);
3695
                    double minLineX = Math.Min(point1[0], point2[0]);
3696
                    double maxLineY = Math.Max(point1[1], point2[1]);
3697
                    double minLineY = Math.Min(point1[1], point2[1]);
3698

    
3699
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3700

    
3701
                    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]);
3702
                    if (crossingPoint != null)
3703
                    {
3704
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3705
                        if (length >= distance)
3706
                        {
3707
                            if (slope == SlopeType.Slope &&
3708
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3709
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3710
                            {
3711
                                targetConnector = item.Key;
3712
                                length = distance;
3713
                                resultPoint = crossingPoint;
3714
                                targetVertices = item.Value;
3715
                            }
3716
                            else if (slope == SlopeType.HORIZONTAL &&
3717
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3718
                            {
3719
                                targetConnector = item.Key;
3720
                                length = distance;
3721
                                resultPoint = crossingPoint;
3722
                                targetVertices = item.Value;
3723
                            }
3724
                            else if (slope == SlopeType.VERTICAL &&
3725
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3726
                            {
3727
                                targetConnector = item.Key;
3728
                                length = distance;
3729
                                resultPoint = crossingPoint;
3730
                                targetVertices = item.Value;
3731
                            }
3732
                        }
3733
                    }
3734
                }
3735
            }
3736

    
3737
            foreach (var item in vertices)
3738
                if (item.Key != null && item.Key != targetConnector)
3739
                    ReleaseCOMObjects(item.Key);
3740

    
3741
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3742
            {
3743
                double tempResultX = resultPoint[0];
3744
                double tempResultY = resultPoint[1];
3745
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3746

    
3747
                GridSetting gridSetting = GridSetting.GetInstance();
3748

    
3749
                for (int i = 0; i < targetVertices.Count; i++)
3750
                {
3751
                    double[] point = targetVertices[i];
3752
                    double tempX = targetVertices[i][0];
3753
                    double tempY = targetVertices[i][1];
3754
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3755
                    if (tempX == tempResultX && tempY == tempResultY)
3756
                    {
3757
                        if (i == 0)
3758
                        {
3759
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3760
                            bool containZeroLength = false;
3761
                            if (connSymbol != null)
3762
                            {
3763
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3764
                                {
3765
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3766
                                        containZeroLength = true;
3767
                                }
3768
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3769
                                {
3770
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3771
                                        containZeroLength = true;
3772
                                }
3773
                            }
3774

    
3775
                            if (connSymbol == null ||
3776
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3777
                                containZeroLength)
3778
                            {
3779
                                bool bCalcX = false;
3780
                                bool bCalcY = false;
3781
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3782
                                    bCalcX = true;
3783
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3784
                                    bCalcY = true;
3785
                                else
3786
                                {
3787
                                    bCalcX = true;
3788
                                    bCalcY = true;
3789
                                }
3790

    
3791
                                if (bCalcX)
3792
                                {
3793
                                    double nextX = targetVertices[i + 1][0];
3794
                                    double newX = 0;
3795
                                    if (nextX > tempX)
3796
                                    {
3797
                                        newX = tempX + gridSetting.Length;
3798
                                        if (newX > nextX)
3799
                                            newX = (point[0] + nextX) / 2;
3800
                                    }
3801
                                    else
3802
                                    {
3803
                                        newX = tempX - gridSetting.Length;
3804
                                        if (newX < nextX)
3805
                                            newX = (point[0] + nextX) / 2;
3806
                                    }
3807
                                    resultPoint = new double[] { newX, resultPoint[1] };
3808
                                }
3809

    
3810
                                if (bCalcY)
3811
                                {
3812
                                    double nextY = targetVertices[i + 1][1];
3813
                                    double newY = 0;
3814
                                    if (nextY > tempY)
3815
                                    {
3816
                                        newY = tempY + gridSetting.Length;
3817
                                        if (newY > nextY)
3818
                                            newY = (point[1] + nextY) / 2;
3819
                                    }
3820
                                    else
3821
                                    {
3822
                                        newY = tempY - gridSetting.Length;
3823
                                        if (newY < nextY)
3824
                                            newY = (point[1] + nextY) / 2;
3825
                                    }
3826
                                    resultPoint = new double[] { resultPoint[0], newY };
3827
                                }
3828
                            }
3829
                        }
3830
                        else if (i == targetVertices.Count - 1)
3831
                        {
3832
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3833
                            bool containZeroLength = false;
3834
                            if (connSymbol != null)
3835
                            {
3836
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3837
                                {
3838
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3839
                                        containZeroLength = true;
3840
                                }
3841
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3842
                                {
3843
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3844
                                        containZeroLength = true;
3845
                                }
3846
                            }
3847

    
3848
                            if (connSymbol == null ||
3849
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3850
                                containZeroLength)
3851
                            {
3852
                                bool bCalcX = false;
3853
                                bool bCalcY = false;
3854
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3855
                                    bCalcX = true;
3856
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3857
                                    bCalcY = true;
3858
                                else
3859
                                {
3860
                                    bCalcX = true;
3861
                                    bCalcY = true;
3862
                                }
3863

    
3864
                                if (bCalcX)
3865
                                {
3866
                                    double nextX = targetVertices[i - 1][0];
3867
                                    double newX = 0;
3868
                                    if (nextX > tempX)
3869
                                    {
3870
                                        newX = tempX + gridSetting.Length;
3871
                                        if (newX > nextX)
3872
                                            newX = (point[0] + nextX) / 2;
3873
                                    }
3874
                                    else
3875
                                    {
3876
                                        newX = tempX - gridSetting.Length;
3877
                                        if (newX < nextX)
3878
                                            newX = (point[0] + nextX) / 2;
3879
                                    }
3880
                                    resultPoint = new double[] { newX, resultPoint[1] };
3881
                                }
3882

    
3883
                                if (bCalcY)
3884
                                {
3885
                                    double nextY = targetVertices[i - 1][1];
3886
                                    double newY = 0;
3887
                                    if (nextY > tempY)
3888
                                    {
3889
                                        newY = tempY + gridSetting.Length;
3890
                                        if (newY > nextY)
3891
                                            newY = (point[1] + nextY) / 2;
3892
                                    }
3893
                                    else
3894
                                    {
3895
                                        newY = tempY - gridSetting.Length;
3896
                                        if (newY < nextY)
3897
                                            newY = (point[1] + nextY) / 2;
3898
                                    }
3899
                                    resultPoint = new double[] { resultPoint[0], newY };
3900
                                }
3901
                            }
3902
                        }
3903
                        break;
3904
                    }
3905
                }
3906
            }
3907

    
3908
            x = resultPoint[0];
3909
            y = resultPoint[1];
3910

    
3911
            return targetConnector;
3912
        }
3913

    
3914
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3915
        {
3916
            LMConnector result = null;
3917
            List<LMConnector> connectors = new List<LMConnector>();
3918
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3919

    
3920
            if (modelItem != null)
3921
            {
3922
                foreach (LMRepresentation rep in modelItem.Representations)
3923
                {
3924
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3925
                        connectors.Add(dataSource.GetConnector(rep.Id));
3926
                }
3927

    
3928
                ReleaseCOMObjects(modelItem);
3929
            }
3930

    
3931
            if (connectors.Count == 1)
3932
                result = connectors[0];
3933
            else
3934
                foreach (var item in connectors)
3935
                    ReleaseCOMObjects(item);
3936

    
3937
            return result;
3938
        }
3939

    
3940
        private int GetConnectorCount(string modelItemID)
3941
        {
3942
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3943
            int result = 0;
3944
            if (modelItem != null)
3945
            {
3946
                foreach (LMRepresentation rep in modelItem.Representations)
3947
                {
3948
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3949
                        result++;
3950
                    ReleaseCOMObjects(rep);
3951
                }
3952
                ReleaseCOMObjects(modelItem);
3953
            }
3954

    
3955
            return result;
3956
        }
3957

    
3958
        public List<string> GetRepresentations(string modelItemID)
3959
        {
3960
            List<string> result = new List<string>(); ;
3961
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3962
            if (modelItem != null)
3963
            {
3964
                foreach (LMRepresentation rep in modelItem.Representations)
3965
                {
3966
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3967
                        result.Add(rep.Id);
3968
                }
3969
                ReleaseCOMObjects(modelItem);
3970
            }
3971

    
3972
            return result;
3973
        }
3974

    
3975
        /// <summary>
3976
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3977
        /// </summary>
3978
        /// <param name="lineNumber"></param>
3979
        private void LineNumberModelingOnlyOne(Line line)
3980
        {
3981
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3982
            if (lineNumber != null)
3983
            {
3984
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3985
                if (connectedLMConnector != null)
3986
                {
3987
                    double x = 0;
3988
                    double y = 0;
3989
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3990

    
3991
                    Array points = new double[] { 0, x, y };
3992
                    lineNumber.SPPID.SPPID_X = x;
3993
                    lineNumber.SPPID.SPPID_Y = y;
3994
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3995

    
3996
                    if (_LmLabelPresist != null)
3997
                    {
3998
                        _LmLabelPresist.Commit();
3999
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4000
                        ReleaseCOMObjects(_LmLabelPresist);
4001
                    }
4002
                }
4003
            }
4004
        }
4005

    
4006
        private void LineNumberModeling(LineNumber lineNumber)
4007
        {
4008
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4009
            if (line != null)
4010
            {
4011
                double x = 0;
4012
                double y = 0;
4013
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4014

    
4015
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4016
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4017
                if (connectedLMConnector != null)
4018
                {
4019
                    Array points = new double[] { 0, x, y };
4020
                    lineNumber.SPPID.SPPID_X = x;
4021
                    lineNumber.SPPID.SPPID_Y = y;
4022
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4023

    
4024
                    if (_LmLabelPresist != null)
4025
                    {
4026
                        _LmLabelPresist.Commit();
4027
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4028
                        ReleaseCOMObjects(_LmLabelPresist);
4029
                    }
4030
                }
4031

    
4032
                foreach (var item in connectorVertices)
4033
                    ReleaseCOMObjects(item.Key);
4034
            }
4035
        }
4036
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4037
        {
4038
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4039
            if (line == null || line.SPPID.Vertices == null)
4040
                return;
4041

    
4042
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4043
            {
4044
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4045
                if (removeLabel != null)
4046
                {
4047
                    GridSetting gridSetting = GridSetting.GetInstance();
4048
                    double[] labelRange = null;
4049
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4050
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4051
                    List<double[]> vertices = GetConnectorVertices(connector);
4052

    
4053
                    double[] resultStart = null;
4054
                    double[] resultEnd = null;
4055
                    double distance = double.MaxValue;
4056
                    for (int i = 0; i < vertices.Count - 1; i++)
4057
                    {
4058
                        double[] startPoint = vertices[i];
4059
                        double[] endPoint = vertices[i + 1];
4060
                        foreach (var item in line.SPPID.Vertices)
4061
                        {
4062
                            double[] lineStartPoint = item[0];
4063
                            double[] lineEndPoint = item[item.Count - 1];
4064

    
4065
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4066
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4067
                            if (tempDistance < distance)
4068
                            {
4069
                                distance = tempDistance;
4070
                                resultStart = startPoint;
4071
                                resultEnd = endPoint;
4072
                            }
4073
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4074
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4075
                            if (tempDistance < distance)
4076
                            {
4077
                                distance = tempDistance;
4078
                                resultStart = startPoint;
4079
                                resultEnd = endPoint;
4080
                            }
4081
                        }
4082
                    }
4083

    
4084
                    if (resultStart != null && resultEnd != null)
4085
                    {
4086
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4087
                        double lineStartX = 0;
4088
                        double lineStartY = 0;
4089
                        double lineEndX = 0;
4090
                        double lineEndY = 0;
4091
                        double lineNumberX = 0;
4092
                        double lineNumberY = 0;
4093
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4094
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4095

    
4096
                        double lineX = (lineStartX + lineEndX) / 2;
4097
                        double lineY = (lineStartY + lineEndY) / 2;
4098
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4099
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4100

    
4101
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4102
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4103
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4104
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4105

    
4106
                        double offsetX = 0;
4107
                        double offsetY = 0;
4108
                        if (slope == SlopeType.HORIZONTAL)
4109
                        {
4110
                            // Line Number 아래
4111
                            if (lineY < lineNumberY)
4112
                            {
4113
                                offsetX = labelCenterX - SPPIDCenterX;
4114
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4115
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4116
                            }
4117
                            // Line Number 위
4118
                            else
4119
                            {
4120
                                offsetX = labelCenterX - SPPIDCenterX;
4121
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4122
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4123
                            }
4124
                        }
4125
                        else if (slope == SlopeType.VERTICAL)
4126
                        {
4127
                            // Line Number 오르쪽
4128
                            if (lineX < lineNumberX)
4129
                            {
4130
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4131
                                offsetY = labelCenterY - SPPIDCenterY;
4132
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4133
                            }
4134
                            // Line Number 왼쪽
4135
                            else
4136
                            {
4137
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4138
                                offsetY = labelCenterY - SPPIDCenterY;
4139
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4140
                            }
4141
                        }
4142

    
4143
                        if (offsetY != 0 && offsetY != 0)
4144
                        {
4145
                            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4146
                            Array points = new double[] { 0, lineNumber.SPPID.SPPID_X, lineNumber.SPPID.SPPID_Y };
4147
                            LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connector.AsLMRepresentation(), IsLeaderVisible: false);
4148

    
4149
                            if (_LmLabelPresist != null)
4150
                            {
4151
                                _LmLabelPresist.Commit();
4152
                                lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4153
                            }
4154
                            ReleaseCOMObjects(_LmLabelPresist);
4155
                            _LmLabelPresist = null; 
4156
                        }
4157

    
4158
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4159
                        {
4160
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4161
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4162
                        }
4163
                    }
4164

    
4165

    
4166
                    ReleaseCOMObjects(connector);
4167
                    connector = null;
4168
                }
4169

    
4170
                ReleaseCOMObjects(removeLabel);
4171
                removeLabel = null;
4172
            }
4173
        }
4174
        /// <summary>
4175
        /// Flow Mark Modeling
4176
        /// </summary>
4177
        /// <param name="line"></param>
4178
        private void FlowMarkModeling(Line line)
4179
        {
4180
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4181
            {
4182
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4183
                if (connector != null)
4184
                {
4185
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4186
                    List<double[]> vertices = GetConnectorVertices(connector);
4187
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4188
                    double[] point = vertices[vertices.Count - 1];
4189
                    Array array = new double[] { 0, point[0], point[1] };
4190
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4191
                    if (_LMLabelPersist != null)
4192
                    {
4193
                        _LMLabelPersist.Commit();
4194
                        ReleaseCOMObjects(_LMLabelPersist);
4195
                    }
4196
                        
4197
                }
4198
            }
4199
        }
4200

    
4201
        /// <summary>
4202
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4203
        /// </summary>
4204
        /// <param name="lineNumber"></param>
4205
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4206
        {
4207
            foreach (LineRun run in lineNumber.RUNS)
4208
            {
4209
                foreach (var item in run.RUNITEMS)
4210
                {
4211
                    if (item.GetType() == typeof(Symbol))
4212
                    {
4213
                        Symbol symbol = item as Symbol;
4214
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4215
                        if (_LMSymbol != null)
4216
                        {
4217
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4218

    
4219
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4220
                            {
4221
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4222
                                {
4223
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4224
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4225
                                    {
4226
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4227
                                        if (_LMAAttribute != null)
4228
                                        {
4229
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4230
                                                _LMAAttribute.set_Value(attribute.VALUE);
4231
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4232
                                                _LMAAttribute.set_Value(attribute.VALUE);
4233
                                        }
4234
                                    }
4235
                                }
4236
                                _LMModelItem.Commit();
4237
                            }
4238
                            if (_LMModelItem != null)
4239
                                ReleaseCOMObjects(_LMModelItem);
4240
                        }
4241
                        if (_LMSymbol != null)
4242
                            ReleaseCOMObjects(_LMSymbol);
4243
                    }
4244
                    else if (item.GetType() == typeof(Line))
4245
                    {
4246
                        Line line = item as Line;
4247
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4248
                        {
4249
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4250
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4251
                            {
4252
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4253
                                {
4254
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4255
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4256
                                    {
4257
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4258
                                        if (_LMAAttribute != null)
4259
                                        {
4260
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4261
                                                _LMAAttribute.set_Value(attribute.VALUE);
4262
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4263
                                                _LMAAttribute.set_Value(attribute.VALUE);
4264

    
4265
                                        }
4266
                                    }
4267
                                }
4268
                                _LMModelItem.Commit();
4269
                            }
4270
                            if (_LMModelItem != null)
4271
                                ReleaseCOMObjects(_LMModelItem);
4272
                            endLine.Add(line.SPPID.ModelItemId);
4273
                        }
4274
                    }
4275
                }
4276
            }
4277
        }
4278

    
4279
        /// <summary>
4280
        /// Symbol Attribute 입력 메서드
4281
        /// </summary>
4282
        /// <param name="item"></param>
4283
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4284
        {
4285
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4286
            string sRep = null;
4287
            if (targetItem.GetType() == typeof(Symbol))
4288
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4289
            else if (targetItem.GetType() == typeof(Equipment))
4290
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4291

    
4292
            if (!string.IsNullOrEmpty(sRep))
4293
            {
4294
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4295
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4296
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4297
                
4298
                foreach (var item in targetAttributes)
4299
                {
4300
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4301
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4302
                    {
4303
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4304
                        if (_Attribute != null)
4305
                        {
4306
                            //object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
4307
                            //if (associItem != null)
4308
                            //{
4309
                            //    if (associItem.GetType() == typeof(Text))
4310
                            //    {
4311
                            //        Text text = associItem as Text;
4312
                            //        text.SPPID.RepresentationId = "Attribute";
4313
                            //    }
4314
                            //    else if (associItem.GetType() == typeof(Note))
4315
                            //    {
4316
                            //        Note note = associItem as Note;
4317
                            //        note.SPPID.RepresentationId = "Attribute";
4318
                            //    }
4319
                            //}
4320
                            _Attribute.set_Value(item.VALUE);
4321
                            // OPC 일경우 Attribute 저장
4322
                            if (targetItem.GetType() == typeof(Symbol))
4323
                            {
4324
                                Symbol symbol = targetItem as Symbol;
4325
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4326
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4327
                            }
4328
                        }
4329
                    }
4330
                }
4331
                _LMModelItem.Commit();
4332

    
4333
                ReleaseCOMObjects(_Attributes);
4334
                ReleaseCOMObjects(_LMModelItem);
4335
                ReleaseCOMObjects(_LMSymbol);
4336
            }
4337
        }
4338

    
4339
        /// <summary>
4340
        /// Input SpecBreak Attribute
4341
        /// </summary>
4342
        /// <param name="specBreak"></param>
4343
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4344
        {
4345
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4346
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4347

    
4348
            if (upStreamObj != null &&
4349
                downStreamObj != null)
4350
            {
4351
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4352

    
4353
                if (targetLMConnector != null)
4354
                {
4355
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4356
                    {
4357
                        string symbolPath = _LMLabelPersist.get_FileName();
4358
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4359
                        if (mapping != null)
4360
                        {
4361
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4362
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4363
                            {
4364
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4365
                                if (values.Length == 2)
4366
                                {
4367
                                    string upStreamValue = values[0];
4368
                                    string downStreamValue = values[1];
4369

    
4370
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4371
                                }
4372
                            }
4373
                        }
4374
                    }
4375

    
4376
                    ReleaseCOMObjects(targetLMConnector);
4377
                }
4378
            }
4379

    
4380

    
4381
            #region 내부에서만 쓰는 메서드
4382
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4383
            {
4384
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4385
                Line upStreamLine = _upStreamObj as Line;
4386
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4387
                Line downStreamLine = _downStreamObj as Line;
4388
                // 둘다 Line일 경우
4389
                if (upStreamLine != null && downStreamLine != null)
4390
                {
4391
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4392
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4393
                }
4394
                // 둘다 Symbol일 경우
4395
                else if (upStreamSymbol != null && downStreamSymbol != null)
4396
                {
4397
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4398
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4399
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4400

    
4401
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4402
                    {
4403
                        if (connector.get_ItemStatus() != "Active")
4404
                            continue;
4405

    
4406
                        if (connector.Id != zeroLenthConnector.Id)
4407
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4408
                    }
4409

    
4410
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4411
                    {
4412
                        if (connector.get_ItemStatus() != "Active")
4413
                            continue;
4414

    
4415
                        if (connector.Id != zeroLenthConnector.Id)
4416
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4417
                    }
4418

    
4419
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4420
                    {
4421
                        if (connector.get_ItemStatus() != "Active")
4422
                            continue;
4423

    
4424
                        if (connector.Id != zeroLenthConnector.Id)
4425
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4426
                    }
4427

    
4428
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4429
                    {
4430
                        if (connector.get_ItemStatus() != "Active")
4431
                            continue;
4432

    
4433
                        if (connector.Id != zeroLenthConnector.Id)
4434
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4435
                    }
4436

    
4437
                    ReleaseCOMObjects(zeroLenthConnector);
4438
                    ReleaseCOMObjects(upStreamLMSymbol);
4439
                    ReleaseCOMObjects(downStreamLMSymbol);
4440
                }
4441
                else if (upStreamSymbol != null && downStreamLine != null)
4442
                {
4443
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4444
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4445
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4446

    
4447
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4448
                    {
4449
                        if (connector.get_ItemStatus() != "Active")
4450
                            continue;
4451

    
4452
                        if (connector.Id == zeroLenthConnector.Id)
4453
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4454
                    }
4455

    
4456
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4457
                    {
4458
                        if (connector.get_ItemStatus() != "Active")
4459
                            continue;
4460

    
4461
                        if (connector.Id == zeroLenthConnector.Id)
4462
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4463
                    }
4464

    
4465
                    ReleaseCOMObjects(zeroLenthConnector);
4466
                    ReleaseCOMObjects(upStreamLMSymbol);
4467
                }
4468
                else if (upStreamLine != null && downStreamSymbol != null)
4469
                {
4470
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4471
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4472
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4473

    
4474
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4475
                    {
4476
                        if (connector.get_ItemStatus() != "Active")
4477
                            continue;
4478

    
4479
                        if (connector.Id == zeroLenthConnector.Id)
4480
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4481
                    }
4482

    
4483
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4484
                    {
4485
                        if (connector.get_ItemStatus() != "Active")
4486
                            continue;
4487

    
4488
                        if (connector.Id == zeroLenthConnector.Id)
4489
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4490
                    }
4491

    
4492
                    ReleaseCOMObjects(zeroLenthConnector);
4493
                    ReleaseCOMObjects(downStreamLMSymbol);
4494
                }
4495
            }
4496

    
4497
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4498
            {
4499
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4500
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4501
                {
4502
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4503
                    if (_LMAAttribute != null)
4504
                    {
4505
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4506
                            _LMAAttribute.set_Value(value);
4507
                        else if (_LMAAttribute.get_Value() != value)
4508
                            _LMAAttribute.set_Value(value);
4509
                    }
4510

    
4511
                    _LMModelItem.Commit();
4512
                }
4513
                if (_LMModelItem != null)
4514
                    ReleaseCOMObjects(_LMModelItem);
4515
            }
4516

    
4517
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4518
            {
4519
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4520
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4521
                {
4522
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4523
                    if (_LMAAttribute != null)
4524
                    {
4525
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4526
                            _LMAAttribute.set_Value(value);
4527
                        else if (_LMAAttribute.get_Value() != value)
4528
                            _LMAAttribute.set_Value(value);
4529
                    }
4530

    
4531
                    _LMModelItem.Commit();
4532
                }
4533
                if (_LMModelItem != null)
4534
                    ReleaseCOMObjects(_LMModelItem);
4535
            }
4536
            #endregion
4537
        }
4538

    
4539
        private void InputEndBreakAttribute(EndBreak endBreak)
4540
        {
4541
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4542
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4543

    
4544
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4545
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4546
            {
4547
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4548
                if (labelPersist != null)
4549
                {
4550
                    LMRepresentation representation = labelPersist.RepresentationObject;
4551
                    if (representation != null)
4552
                    {
4553
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4554
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4555
                        string modelItemID = connector.ModelItemID;
4556
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4557
                        {
4558
                            List<string> modelItemIDs = new List<string>();
4559
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4560
                            {
4561
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4562
                                foreach (LMConnector item in symbol.Connect1Connectors)
4563
                                {
4564
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4565
                                        modelItemIDs.Add(item.ModelItemID);
4566
                                    ReleaseCOMObjects(item);
4567
                                }
4568
                                foreach (LMConnector item in symbol.Connect2Connectors)
4569
                                {
4570
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4571
                                        modelItemIDs.Add(item.ModelItemID);
4572
                                    ReleaseCOMObjects(item);
4573
                                }
4574
                                ReleaseCOMObjects(symbol);
4575
                                symbol = null;
4576
                            }
4577
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4578
                            {
4579
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4580
                                foreach (LMConnector item in symbol.Connect1Connectors)
4581
                                {
4582
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4583
                                        modelItemIDs.Add(item.ModelItemID);
4584
                                    ReleaseCOMObjects(item);
4585
                                }
4586
                                foreach (LMConnector item in symbol.Connect2Connectors)
4587
                                {
4588
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4589
                                        modelItemIDs.Add(item.ModelItemID);
4590
                                    ReleaseCOMObjects(item);
4591
                                }
4592
                                ReleaseCOMObjects(symbol);
4593
                                symbol = null;
4594
                            }
4595

    
4596
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4597
                            if (modelItemIDs.Count == 1)
4598
                            {
4599
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4600
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4601
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4602
                                {
4603
                                    bool result = false;
4604
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4605
                                    {
4606
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4607
                                            result = true;
4608
                                        ReleaseCOMObjects(loop);
4609
                                    }
4610

    
4611
                                    if (result)
4612
                                    {
4613
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4614
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4615
                                        ZeroLengthModelItem.Commit();
4616
                                    }
4617
                                    else
4618
                                    {
4619
                                        List<string> loopModelItems = new List<string>();
4620
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
4621
                                        {
4622
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
4623
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4624
                                            {
4625
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4626
                                                    loopModelItems.Add(loop.ModelItemID);
4627
                                                ReleaseCOMObjects(loop);
4628
                                            }
4629
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4630
                                            {
4631
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4632
                                                    loopModelItems.Add(loop.ModelItemID);
4633
                                                ReleaseCOMObjects(loop);
4634
                                            }
4635
                                            ReleaseCOMObjects(_symbol);
4636
                                            _symbol = null;
4637
                                        }
4638
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
4639
                                        {
4640
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
4641
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4642
                                            {
4643
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4644
                                                    loopModelItems.Add(loop.ModelItemID);
4645
                                                ReleaseCOMObjects(loop);
4646
                                            }
4647
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4648
                                            {
4649
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4650
                                                    loopModelItems.Add(loop.ModelItemID);
4651
                                                ReleaseCOMObjects(loop);
4652
                                            }
4653
                                            ReleaseCOMObjects(_symbol);
4654
                                            _symbol = null;
4655
                                        }
4656

    
4657
                                        loopModelItems = loopModelItems.Distinct().ToList();
4658
                                        if (loopModelItems.Count == 1)
4659
                                        {
4660
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
4661
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
4662
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
4663
                                            modelItem.Commit();
4664
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4665
                                            ZeroLengthModelItem.Commit();
4666

    
4667
                                            ReleaseCOMObjects(loopModelItem);
4668
                                            loopModelItem = null;
4669
                                        }
4670
                                    }
4671
                                }
4672
                                else
4673
                                {
4674
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4675
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4676
                                    ZeroLengthModelItem.Commit();
4677
                                }
4678
                                ReleaseCOMObjects(modelItem);
4679
                                modelItem = null;
4680
                                ReleaseCOMObjects(onlyOne);
4681
                                onlyOne = null;
4682
                            }
4683
                        }
4684
                        ReleaseCOMObjects(connector);
4685
                        connector = null;
4686
                        ReleaseCOMObjects(ZeroLengthModelItem);
4687
                        ZeroLengthModelItem = null;
4688
                    }
4689
                    ReleaseCOMObjects(representation);
4690
                    representation = null;
4691
                }
4692
                ReleaseCOMObjects(labelPersist);
4693
                labelPersist = null;
4694
            }
4695
        }
4696

    
4697
        /// <summary>
4698
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
4699
        /// </summary>
4700
        /// <param name="text"></param>
4701
        private void NormalTextModeling(Text text)
4702
        {
4703
            LMSymbol _LMSymbol = null;
4704

    
4705
            LMItemNote _LMItemNote = null;
4706
            LMAAttribute _LMAAttribute = null;
4707

    
4708
            double x = 0;
4709
            double y = 0;
4710
            double angle = text.ANGLE;
4711
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
4712

    
4713
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4714
            text.SPPID.SPPID_X = x;
4715
            text.SPPID.SPPID_Y = y;
4716

    
4717
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
4718
            if (_LMSymbol != null)
4719
            {
4720
                _LMSymbol.Commit();
4721
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4722
                if (_LMItemNote != null)
4723
                {
4724
                    _LMItemNote.Commit();
4725
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4726
                    if (_LMAAttribute != null)
4727
                    {
4728
                        _LMAAttribute.set_Value(text.VALUE);
4729
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4730
                        _LMItemNote.Commit();
4731

    
4732

    
4733
                        double[] range = null;
4734
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4735
                        {
4736
                            double[] temp = null;
4737
                            GetSPPIDSymbolRange(labelPersist, ref temp);
4738
                            if (temp != null)
4739
                            {
4740
                                if (range == null)
4741
                                    range = temp;
4742
                                else
4743
                                {
4744
                                    range = new double[] {
4745
                                            Math.Min(range[0], temp[0]),
4746
                                            Math.Min(range[1], temp[1]),
4747
                                            Math.Max(range[2], temp[2]),
4748
                                            Math.Max(range[3], temp[3])
4749
                                        };
4750
                                }
4751
                            }
4752
                        }
4753
                        text.SPPID.Range = range;
4754

    
4755
                        if (_LMAAttribute != null)
4756
                            ReleaseCOMObjects(_LMAAttribute);
4757
                        if (_LMItemNote != null)
4758
                            ReleaseCOMObjects(_LMItemNote);
4759
                    }
4760

    
4761
                    TextCorrectModeling(text);
4762
                }
4763
            }
4764
            if (_LMSymbol != null)
4765
                ReleaseCOMObjects(_LMSymbol);
4766
        }
4767

    
4768
        private void AssociationTextModeling(Text text)
4769
        {
4770
            LMSymbol _LMSymbol = null;
4771
            LMConnector connectedLMConnector = null;
4772
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4773
            if (owner != null && owner.GetType() == typeof(Symbol))
4774
            {
4775
                Symbol symbol = owner as Symbol;
4776
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4777
                if (_LMSymbol != null)
4778
                {
4779
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4780
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4781
                    {
4782
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4783

    
4784
                        if (mapping != null)
4785
                        {
4786
                            double x = 0;
4787
                            double y = 0;
4788

    
4789
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4790
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4791
                            Array array = new double[] { 0, x, y };
4792
                            text.SPPID.SPPID_X = x;
4793
                            text.SPPID.SPPID_Y = y;
4794
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4795
                            if (_LMLabelPersist != null)
4796
                            {
4797
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4798
                                _LMLabelPersist.Commit();
4799
                                ReleaseCOMObjects(_LMLabelPersist);
4800
                            }
4801
                        }
4802
                    }
4803
                }
4804
            }
4805
            else if (owner != null && owner.GetType() == typeof(Line))
4806
            {
4807
                Line line = owner as Line;
4808
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4809
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
4810

    
4811
                if (connectedLMConnector != null)
4812
                {
4813
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4814
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4815
                    {
4816
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4817

    
4818
                        if (mapping != null)
4819
                        {
4820
                            double x = 0;
4821
                            double y = 0;
4822
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4823
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4824
                            Array array = new double[] { 0, x, y };
4825

    
4826
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4827
                            if (_LMLabelPersist != null)
4828
                            {
4829
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4830
                                _LMLabelPersist.Commit();
4831
                                ReleaseCOMObjects(_LMLabelPersist);
4832
                            }
4833
                        }
4834
                    }
4835
                }
4836
            }
4837
            if (_LMSymbol != null)
4838
                ReleaseCOMObjects(_LMSymbol);
4839
        }
4840

    
4841
        private void TextCorrectModeling(Text text)
4842
        {
4843
            if (text.SPPID.Range == null)
4844
                return;
4845

    
4846
            bool needRemodeling = false;
4847
            bool loop = true;
4848
            GridSetting gridSetting = GridSetting.GetInstance();
4849
            while (loop)
4850
            {
4851
                loop = false;
4852
                foreach (var overlapText in document.TEXTINFOS)
4853
                {
4854
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
4855
                        continue;
4856

    
4857
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
4858
                    {
4859
                        double percentX = 0;
4860
                        double percentY = 0;
4861
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
4862
                        {
4863
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
4864
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
4865
                        }
4866
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
4867
                        {
4868
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
4869
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
4870
                        }
4871

    
4872
                        double tempX = 0;
4873
                        double tempY = 0;
4874
                        bool overlapX = false;
4875
                        bool overlapY = false;
4876
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4877
                        if (percentX >= percentY)
4878
                        {
4879
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4880
                            double move = gridSetting.Length * count;
4881
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
4882
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
4883
                            needRemodeling = true;
4884
                            loop = true;
4885
                        }
4886
                        else
4887
                        {
4888
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4889
                            double move = gridSetting.Length * count;
4890
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
4891
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
4892
                            needRemodeling = true;
4893
                            loop = true;
4894
                        }
4895
                    }
4896
                }
4897
            }
4898
            
4899

    
4900
            if (needRemodeling)
4901
            {
4902
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
4903
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4904
                text.SPPID.RepresentationId = null;
4905

    
4906
                LMItemNote _LMItemNote = null;
4907
                LMAAttribute _LMAAttribute = null;
4908
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
4909
                if (_LMSymbol != null)
4910
                {
4911
                    _LMSymbol.Commit();
4912
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4913
                    if (_LMItemNote != null)
4914
                    {
4915
                        _LMItemNote.Commit();
4916
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4917
                        if (_LMAAttribute != null)
4918
                        {
4919
                            _LMAAttribute.set_Value(text.VALUE);
4920
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4921
                            _LMItemNote.Commit();
4922

    
4923
                            ReleaseCOMObjects(_LMAAttribute);
4924
                            ReleaseCOMObjects(_LMItemNote);
4925
                        }
4926
                    }
4927
                }
4928

    
4929
                ReleaseCOMObjects(symbol);
4930
                symbol = null;
4931
                ReleaseCOMObjects(_LMItemNote);
4932
                _LMItemNote = null;
4933
                ReleaseCOMObjects(_LMAAttribute);
4934
                _LMAAttribute = null;
4935
                ReleaseCOMObjects(_LMSymbol);
4936
                _LMSymbol = null;
4937
            }
4938
        }
4939

    
4940
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
4941
        {
4942
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
4943
            {
4944
                List<Text> texts = new List<Text>();
4945
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
4946
                LMRepresentation representation = targetLabel.RepresentationObject;
4947
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
4948
                if (targetLabel.RepresentationObject != null && symbol != null)
4949
                {
4950
                    double[] symbolRange = null;
4951
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
4952
                    if (symbolRange != null)
4953
                    {
4954
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
4955
                        {
4956
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
4957
                            if (findText != null)
4958
                            {
4959
                                double[] range = null;
4960
                                GetSPPIDSymbolRange(labelPersist, ref range);
4961
                                findText.SPPID.Range = range;
4962
                                texts.Add(findText);
4963
                            }
4964

    
4965
                            ReleaseCOMObjects(labelPersist);
4966
                        }
4967

    
4968
                        if (texts.Count > 0)
4969
                        {
4970
                            #region Sort Text By Y
4971
                            texts.Sort(SortTextByY);
4972
                            int SortTextByY(Text a, Text b)
4973
                            {
4974
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
4975
                            }
4976
                            #endregion
4977

    
4978
                            #region 첫번째 Text로 기준 맞춤
4979
                            for (int i = 0; i < texts.Count; i++)
4980
                            {
4981
                                if (i != 0)
4982
                                {
4983
                                    Text currentText = texts[i];
4984
                                    Text prevText = texts[i - 1];
4985
                                    double minY = prevText.SPPID.Range[1];
4986
                                    double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
4987
                                    double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
4988
                                    double _gapX = centerX - centerPrevX;
4989
                                    double _gapY = currentText.SPPID.Range[3] - minY;
4990
                                    MoveText(currentText, _gapX, _gapY);
4991
                                }
4992
                            }
4993
                            List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
4994
                            List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
4995
                            List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
4996
                            List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
4997
                            rangeMinX.Sort();
4998
                            rangeMinY.Sort();
4999
                            rangeMaxX.Sort();
5000
                            rangeMaxY.Sort();
5001
                            double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5002
                            double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5003
                            #endregion
5004

    
5005
                            Text correctBySymbol = texts[0];
5006
                            double textCenterX = (text.X1 + text.X2) / 2;
5007
                            double textCenterY = (text.Y1 + text.Y2) / 2;
5008
                            double originX = 0;
5009
                            double originY = 0;
5010
                            SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5011
                            double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5012
                            double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5013
                            double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5014

    
5015
                            double gapX = 0;
5016
                            double gapY = 0;
5017
                            if (angle < 45)
5018
                            {
5019
                                // Text 오른쪽
5020
                                if (textCenterX > originX)
5021
                                {
5022
                                    gapX = rangeMinX[0] - symbolRange[2];
5023
                                    gapY = allTextCenterY - symbolCenterY;
5024
                                }
5025
                                // Text 왼쪽
5026
                                else
5027
                                {
5028
                                    gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5029
                                    gapY = allTextCenterY - symbolCenterY;
5030
                                }
5031
                            }
5032
                            else
5033
                            {
5034
                                // Text 아래쪽
5035
                                if (textCenterY > originY)
5036
                                {
5037
                                    gapX = allTextCenterX - symbolCenterX;
5038
                                    gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5039
                                }
5040
                                // Text 위쪽
5041
                                else
5042
                                {
5043
                                    gapX = allTextCenterX - symbolCenterX;
5044
                                    gapY = rangeMinY[0] - symbolRange[3];
5045
                                }
5046
                            }
5047

    
5048
                            foreach (var item in texts)
5049
                            {
5050
                                MoveText(item, gapX, gapY);
5051
                                RemodelingAssociationText(item);
5052
                            }
5053
                        }
5054
                    }
5055
                }
5056

    
5057
                void MoveText(Text moveText, double x, double y)
5058
                {
5059
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5060
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5061
                    moveText.SPPID.Range = new double[] {
5062
                        moveText.SPPID.Range[0] - x,
5063
                        moveText.SPPID.Range[1]- y,
5064
                        moveText.SPPID.Range[2]- x,
5065
                        moveText.SPPID.Range[3]- y
5066
                    };
5067
                }
5068

    
5069
                endTexts.AddRange(texts);
5070

    
5071
                ReleaseCOMObjects(targetLabel);
5072
                targetLabel = null;
5073
                ReleaseCOMObjects(representation);
5074
                representation = null;
5075
            }
5076
        }
5077

    
5078
        private void RemodelingAssociationText(Text text)
5079
        {
5080
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5081
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5082
            removeLabel.Commit();
5083
            ReleaseCOMObjects(removeLabel);
5084
            removeLabel = null;
5085

    
5086
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5087
            if (owner != null && owner.GetType() == typeof(Symbol))
5088
            {
5089
                Symbol symbol = owner as Symbol;
5090
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5091
                if (_LMSymbol != null)
5092
                {
5093
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5094
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5095
                    {
5096
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5097

    
5098
                        if (mapping != null)
5099
                        {
5100
                            double x = 0;
5101
                            double y = 0;
5102

    
5103
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5104
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5105
                            if (_LMLabelPersist != null)
5106
                            {
5107
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5108
                                _LMLabelPersist.Commit();
5109
                            }
5110
                            ReleaseCOMObjects(_LMLabelPersist);
5111
                            _LMLabelPersist = null;
5112
                        }
5113
                    }
5114
                }
5115
                ReleaseCOMObjects(_LMSymbol);
5116
                _LMSymbol = null;
5117
            }
5118
        }
5119

    
5120
        /// <summary>
5121
        /// Note Modeling
5122
        /// </summary>
5123
        /// <param name="note"></param>
5124
        private void NoteModeling(Note note, List<Note> correctList)
5125
        {
5126
            LMSymbol _LMSymbol = null;
5127
            LMItemNote _LMItemNote = null;
5128
            LMAAttribute _LMAAttribute = null;
5129

    
5130
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5131
            {
5132
                double x = 0;
5133
                double y = 0;
5134

    
5135
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5136
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5137
                note.SPPID.SPPID_X = x;
5138
                note.SPPID.SPPID_Y = y;
5139

    
5140
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5141
                if (_LMSymbol != null)
5142
                {
5143
                    _LMSymbol.Commit();
5144
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5145
                    if (_LMItemNote != null)
5146
                    {
5147
                        _LMItemNote.Commit();
5148
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5149
                        if (_LMAAttribute != null)
5150
                        {
5151
                            _LMAAttribute.set_Value(note.VALUE);
5152
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5153

    
5154
                            double[] range = null;
5155
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5156
                            {
5157
                                double[] temp = null;
5158
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5159
                                if (temp != null)
5160
                                {
5161
                                    if (range == null)
5162
                                        range = temp;
5163
                                    else
5164
                                    {
5165
                                        range = new double[] {
5166
                                            Math.Min(range[0], temp[0]),
5167
                                            Math.Min(range[1], temp[1]),
5168
                                            Math.Max(range[2], temp[2]),
5169
                                            Math.Max(range[3], temp[3])
5170
                                        };
5171
                                    }
5172
                                }
5173
                            }
5174
                            if (range != null)
5175
                                correctList.Add(note);
5176
                            note.SPPID.Range = range;
5177

    
5178

    
5179
                            _LMItemNote.Commit();
5180
                        }
5181
                    }
5182
                }
5183
            }
5184

    
5185
            if (_LMAAttribute != null)
5186
                ReleaseCOMObjects(_LMAAttribute);
5187
            if (_LMItemNote != null)
5188
                ReleaseCOMObjects(_LMItemNote);
5189
            if (_LMSymbol != null)
5190
                ReleaseCOMObjects(_LMSymbol);
5191
        }
5192

    
5193
        private void NoteCorrectModeling(Note note, List<Note> endList)
5194
        {
5195
            bool needRemodeling = false;
5196
            bool loop = true;
5197
            GridSetting gridSetting = GridSetting.GetInstance();
5198
            while (loop)
5199
            {
5200
                loop = false;
5201
                foreach (var overlap in endList)
5202
                {
5203
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5204
                    {
5205
                        double tempX = 0;
5206
                        double tempY = 0;
5207
                        bool overlapX = false;
5208
                        bool overlapY = false;
5209
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5210
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5211
                        if (overlapY && angle >= 45)
5212
                        {
5213
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5214
                            double move = gridSetting.Length * count;
5215
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5216
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5217
                            needRemodeling = true;
5218
                            loop = true;
5219
                        }
5220
                        if (overlapX && angle <= 45)
5221
                        {
5222
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5223
                            double move = gridSetting.Length * count;
5224
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5225
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5226
                            needRemodeling = true;
5227
                            loop = true;
5228
                        }
5229
                    }
5230
                }
5231
            }
5232

    
5233

    
5234
            if (needRemodeling)
5235
            {
5236
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5237
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5238
                note.SPPID.RepresentationId = null;
5239

    
5240
                LMItemNote _LMItemNote = null;
5241
                LMAAttribute _LMAAttribute = null;
5242
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5243
                if (_LMSymbol != null)
5244
                {
5245
                    _LMSymbol.Commit();
5246
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5247
                    if (_LMItemNote != null)
5248
                    {
5249
                        _LMItemNote.Commit();
5250
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5251
                        if (_LMAAttribute != null)
5252
                        {
5253
                            _LMAAttribute.set_Value(note.VALUE);
5254
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5255
                            _LMItemNote.Commit();
5256

    
5257
                            ReleaseCOMObjects(_LMAAttribute);
5258
                            ReleaseCOMObjects(_LMItemNote);
5259
                        }
5260
                    }
5261
                }
5262

    
5263
                ReleaseCOMObjects(symbol);
5264
                symbol = null;
5265
                ReleaseCOMObjects(_LMItemNote);
5266
                _LMItemNote = null;
5267
                ReleaseCOMObjects(_LMAAttribute);
5268
                _LMAAttribute = null;
5269
                ReleaseCOMObjects(_LMSymbol);
5270
                _LMSymbol = null;
5271
            }
5272

    
5273
            endList.Add(note);
5274
        }
5275

    
5276
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5277
        {
5278
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5279
            if (modelItem != null)
5280
            {
5281
                foreach (LMRepresentation rep in modelItem.Representations)
5282
                {
5283
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5284
                    {
5285
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5286
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5287
                        {
5288
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5289
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5290
                            if (modelItemIds.Count == 1)
5291
                            {
5292
                                string joinModelItemId = modelItemIds[0];
5293
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
5294
                                if (survivorId != null)
5295
                                    break;
5296
                            }
5297
                        }
5298
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5299
                        {
5300
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5301
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5302
                            if (modelItemIds.Count == 1)
5303
                            {
5304
                                string joinModelItemId = modelItemIds[0];
5305
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
5306
                                if (survivorId != null)
5307
                                    break;
5308
                            }
5309
                        }
5310
                    }
5311
                }
5312
            }
5313
        }
5314

    
5315
        /// <summary>
5316
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5317
        /// </summary>
5318
        /// <param name="x"></param>
5319
        /// <param name="y"></param>
5320
        /// <param name="originX"></param>
5321
        /// <param name="originY"></param>
5322
        /// <param name="SPPIDLabelLocation"></param>
5323
        /// <param name="location"></param>
5324
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5325
        {
5326
            if (location == Location.None)
5327
            {
5328
                x = originX;
5329
                y = originY;
5330
            }
5331
            else
5332
            {
5333
                if (location.HasFlag(Location.Center))
5334
                {
5335
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5336
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5337
                }
5338

    
5339
                if (location.HasFlag(Location.Left))
5340
                    x = SPPIDLabelLocation.X1;
5341
                else if (location.HasFlag(Location.Right))
5342
                    x = SPPIDLabelLocation.X2;
5343

    
5344
                if (location.HasFlag(Location.Down))
5345
                    y = SPPIDLabelLocation.Y1;
5346
                else if (location.HasFlag(Location.Up))
5347
                    y = SPPIDLabelLocation.Y2;
5348
            }
5349
        }
5350

    
5351
        /// <summary>
5352
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5353
        /// 1. Angle Valve
5354
        /// 2. 3개로 이루어진 Symbol Group
5355
        /// </summary>
5356
        /// <returns></returns>
5357
        private List<Symbol> GetPrioritySymbol()
5358
        {
5359
            DataTable symbolTable = document.SymbolTable;
5360
            // List에 순서대로 쌓는다.
5361
            List<Symbol> symbols = new List<Symbol>();
5362

    
5363
            // Angle Valve 부터
5364
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5365
            {
5366
                if (!symbols.Contains(symbol))
5367
                {
5368
                    double originX = 0;
5369
                    double originY = 0;
5370

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

    
5375
                    SlopeType slopeType1 = SlopeType.None;
5376
                    SlopeType slopeType2 = SlopeType.None;
5377
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5378
                    {
5379
                        double connectorX = 0;
5380
                        double connectorY = 0;
5381
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5382
                        if (slopeType1 == SlopeType.None)
5383
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5384
                        else
5385
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5386
                    }
5387

    
5388
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5389
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5390
                        symbols.Add(symbol);
5391
                }
5392
            }
5393

    
5394
            List<Symbol> tempSymbols = new List<Symbol>();
5395
            // Conn 갯수 기준
5396
            foreach (var item in document.SYMBOLS)
5397
            {
5398
                if (!symbols.Contains(item))
5399
                    tempSymbols.Add(item);
5400
            }
5401
            tempSymbols.Sort(SortSymbolPriority);
5402
            symbols.AddRange(tempSymbols);
5403

    
5404
            return symbols;
5405
        }
5406

    
5407
        private void SetPriorityLine(List<Line> lines)
5408
        {
5409
            lines.Sort(SortLinePriority);
5410

    
5411
            int SortLinePriority(Line a, Line b)
5412
            {
5413
                // Branch 없는것부터
5414
                int branchRetval = CompareBranchLine(a, b);
5415
                if (branchRetval != 0)
5416
                {
5417
                    return branchRetval;
5418
                }
5419
                else
5420
                {
5421
                    // Symbol 연결 갯수
5422
                    int connSymbolRetval = CompareConnSymbol(a, b);
5423
                    if (connSymbolRetval != 0)
5424
                    {
5425
                        return connSymbolRetval;
5426
                    }
5427
                    else
5428
                    {
5429
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5430
                        int connItemRetval = CompareConnItem(a, b);
5431
                        if (connItemRetval != 0)
5432
                        {
5433
                            return connItemRetval;
5434
                        }
5435
                        else
5436
                        {
5437
                            // ConnectedItem이 없는것
5438
                            int noneConnRetval = CompareNoneConn(a, b);
5439
                            if (noneConnRetval != 0)
5440
                            {
5441
                                return noneConnRetval;
5442
                            }
5443
                            else
5444
                            {
5445

    
5446
                            }
5447
                        }
5448
                    }
5449
                }
5450

    
5451
                return 0;
5452
            }
5453

    
5454
            int CompareNotSegmentLine(Line a, Line b)
5455
            {
5456
                List<Connector> connectorsA = a.CONNECTORS
5457
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5458
                    .ToList();
5459

    
5460
                List<Connector> connectorsB = b.CONNECTORS
5461
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5462
                    .ToList();
5463

    
5464
                // 오름차순
5465
                return connectorsB.Count.CompareTo(connectorsA.Count);
5466
            }
5467

    
5468
            int CompareConnSymbol(Line a, Line b)
5469
            {
5470
                List<Connector> connectorsA = a.CONNECTORS
5471
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5472
                    .ToList();
5473

    
5474
                List<Connector> connectorsB = b.CONNECTORS
5475
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5476
                    .ToList();
5477

    
5478
                // 오름차순
5479
                return connectorsB.Count.CompareTo(connectorsA.Count);
5480
            }
5481

    
5482
            int CompareConnItem(Line a, Line b)
5483
            {
5484
                List<Connector> connectorsA = a.CONNECTORS
5485
                    .Where(conn => conn.ConnectedObject != null && 
5486
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5487
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5488
                    .ToList();
5489

    
5490
                List<Connector> connectorsB = b.CONNECTORS
5491
                    .Where(conn => conn.ConnectedObject != null &&
5492
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5493
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5494
                    .ToList();
5495

    
5496
                // 오름차순
5497
                return connectorsB.Count.CompareTo(connectorsA.Count);
5498
            }
5499

    
5500
            int CompareBranchLine(Line a, Line b)
5501
            {
5502
                List<Connector> connectorsA = a.CONNECTORS
5503
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5504
                    .ToList();
5505
                List<Connector> connectorsB = b.CONNECTORS
5506
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5507
                    .ToList();
5508

    
5509
                // 내림차순
5510
                return connectorsA.Count.CompareTo(connectorsB.Count);
5511
            }
5512

    
5513
            int CompareNoneConn(Line a, Line b)
5514
            {
5515
                List<Connector> connectorsA = a.CONNECTORS
5516
                    .Where(conn => conn.ConnectedObject == null)
5517
                    .ToList();
5518

    
5519
                List<Connector> connectorsB = b.CONNECTORS
5520
                    .Where(conn => conn.ConnectedObject == null)
5521
                    .ToList();
5522

    
5523
                // 오름차순
5524
                return connectorsB.Count.CompareTo(connectorsA.Count);
5525
            }
5526
        }
5527

    
5528
        private void SortText(List<Text> texts)
5529
        {
5530
            texts.Sort(Sort);
5531

    
5532
            int Sort(Text a, Text b)
5533
            {
5534
                int yRetval = CompareY(a, b);
5535
                if (yRetval != 0)
5536
                {
5537
                    return yRetval;
5538
                }
5539
                else
5540
                {
5541
                    return CompareX(a, b);
5542
                }
5543
            }
5544

    
5545
            int CompareY(Text a, Text b)
5546
            {
5547
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5548
            }
5549

    
5550
            int CompareX(Text a, Text b)
5551
            {
5552
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5553
            }
5554
        }
5555
        private void SortNote(List<Note> notes)
5556
        {
5557
            notes.Sort(Sort);
5558

    
5559
            int Sort(Note a, Note b)
5560
            {
5561
                int yRetval = CompareY(a, b);
5562
                if (yRetval != 0)
5563
                {
5564
                    return yRetval;
5565
                }
5566
                else
5567
                {
5568
                    return CompareX(a, b);
5569
                }
5570
            }
5571

    
5572
            int CompareY(Note a, Note b)
5573
            {
5574
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5575
            }
5576

    
5577
            int CompareX(Note a, Note b)
5578
            {
5579
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5580
            }
5581
        }
5582

    
5583
        private void SortBranchLines()
5584
        {
5585
            BranchLines.Sort(SortBranchLine);
5586
            int SortBranchLine(Line a, Line b)
5587
            {
5588
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5589
                 x.ConnectedObject.GetType() == typeof(Line) &&
5590
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
5591
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5592

    
5593
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5594
                 x.ConnectedObject.GetType() == typeof(Line) &&
5595
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
5596
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5597

    
5598
                // 내림차순
5599
                return countA.CompareTo(countB);
5600
            }
5601
        }
5602

    
5603
        private static int SortSymbolPriority(Symbol a, Symbol b)
5604
        {
5605
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5606
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5607
            int retval = countB.CompareTo(countA);
5608
            if (retval != 0)
5609
                return retval;
5610
            else
5611
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
5612
        }
5613

    
5614
        private string GetSPPIDFileName(LMModelItem modelItem)
5615
        {
5616
            string symbolPath = null;
5617
            foreach (LMRepresentation rep in modelItem.Representations)
5618
            {
5619
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5620
                {
5621
                    symbolPath = rep.get_FileName();
5622
                    break;
5623
                }
5624
            }
5625
            return symbolPath;
5626
        }
5627

    
5628
        private string GetSPPIDFileName(string modelItemId)
5629
        {
5630
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5631
            string symbolPath = null;
5632
            foreach (LMRepresentation rep in modelItem.Representations)
5633
            {
5634
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5635
                {
5636
                    symbolPath = rep.get_FileName();
5637
                    break;
5638
                }
5639
            }
5640
            ReleaseCOMObjects(modelItem);
5641
            return symbolPath;
5642
        }
5643

    
5644
        /// <summary>
5645
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
5646
        /// </summary>
5647
        /// <param name="graphicOID"></param>
5648
        /// <param name="milliseconds"></param>
5649
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
5650
        {
5651
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
5652
            {
5653
                double minX = 0;
5654
                double minY = 0;
5655
                double maxX = 0;
5656
                double maxY = 0;
5657
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
5658
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
5659

    
5660
                Thread.Sleep(milliseconds);
5661
            }
5662
        }
5663

    
5664
        /// <summary>
5665
        /// ComObject를 Release
5666
        /// </summary>
5667
        /// <param name="objVars"></param>
5668
        public void ReleaseCOMObjects(params object[] objVars)
5669
        {
5670
            if (objVars != null)
5671
            {
5672
                int intNewRefCount = 0;
5673
                foreach (object obj in objVars)
5674
                {
5675
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
5676
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
5677
                }
5678
            }
5679
        }
5680

    
5681
        /// IDisposable 구현
5682
        ~AutoModeling()
5683
        {
5684
            this.Dispose(false);
5685
        }
5686

    
5687
        private bool disposed;
5688
        public void Dispose()
5689
        {
5690
            this.Dispose(true);
5691
            GC.SuppressFinalize(this);
5692
        }
5693

    
5694
        protected virtual void Dispose(bool disposing)
5695
        {
5696
            if (this.disposed) return;
5697
            if (disposing)
5698
            {
5699
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
5700
            }
5701
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
5702
            this.disposed = true;
5703
        }
5704
    }
5705
}
클립보드 이미지 추가 (최대 크기: 500 MB)