프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ e1c86c6a

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

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

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

    
156
                Log.Write("End Modeling");
157
                radApp.ActiveWindow.Fit();
158

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

    
176
                ReleaseCOMObjects(dataSource);
177
                dataSource = null;
178
                ReleaseCOMObjects(_placement);
179
                _placement = null;
180

    
181
                Thread.Sleep(1000);
182
            }
183
        }
184

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

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

    
233
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
234
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
235

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

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

    
275
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
276
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
277
            foreach (var item in stepLast_Line)
278
            {
279
                try
280
                {
281
                    NewLineModeling(item);
282
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
283
                }
284
                catch (Exception ex)
285
                {
286
                    Log.Write("Error in NewLineModeling");
287
                    Log.Write("UID : " + item.UID);
288
                    Log.Write(ex.Message);
289
                    Log.Write(ex.StackTrace);
290
                }
291
            }
292
        }
293
        private void RunClearNominalDiameter()
294
        {
295
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
296
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
297
            List<string> endClearModelItemID = new List<string>();
298
            for (int i = 0; i < document.LINES.Count; i++)
299
            {
300
                Line item = document.LINES[i];
301
                string modelItemID = item.SPPID.ModelItemId;
302
                if (!string.IsNullOrEmpty(modelItemID))
303
                {
304
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
305
                    if (modelItem != null)
306
                    {
307
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
308
                        if (attribute != null)
309
                            attribute.set_Value(DBNull.Value);
310

    
311
                        modelItem.Commit();
312
                        ReleaseCOMObjects(modelItem);
313
                        modelItem = null;
314
                    }
315
                }
316
                if (!endClearModelItemID.Contains(modelItemID))
317
                    endClearModelItemID.Add(modelItemID);
318
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
319
            }
320
            for (int i = 0; i < document.SYMBOLS.Count; i++)
321
            {
322
                Symbol item = document.SYMBOLS[i];
323
                string repID = item.SPPID.RepresentationId;
324
                string modelItemID = item.SPPID.ModelItemID;
325
                if (!string.IsNullOrEmpty(modelItemID))
326
                {
327
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
328
                    if (modelItem != null)
329
                    {
330
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
331
                        if (attribute != null)
332
                            attribute.set_Value(DBNull.Value);
333
                        int index = 1;
334
                        while (true)
335
                        {
336
                            attribute = modelItem.Attributes[string.Format("PipingPoint{0}.NominalDiameter", index)];
337
                            if (attribute != null)
338
                                attribute.set_Value(DBNull.Value);
339
                            else
340
                                break;
341
                            index++;
342
                        }
343
                        modelItem.Commit();
344
                        ReleaseCOMObjects(modelItem);
345
                        modelItem = null;
346
                    }
347
                }
348
                if (!string.IsNullOrEmpty(repID))
349
                {
350
                    LMSymbol symbol = dataSource.GetSymbol(repID);
351
                    if (symbol != null)
352
                    {
353
                        foreach (LMConnector connector in symbol.Connect1Connectors)
354
                        {
355
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
356
                            {
357
                                endClearModelItemID.Add(connector.ModelItemID);
358
                                LMModelItem modelItem = connector.ModelItemObject;
359
                                if (modelItem != null)
360
                                {
361
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
362
                                    if (attribute != null)
363
                                        attribute.set_Value(DBNull.Value);
364

    
365
                                    modelItem.Commit();
366
                                    ReleaseCOMObjects(modelItem);
367
                                    modelItem = null;
368
                                }
369
                            }
370
                        }
371
                        foreach (LMConnector connector in symbol.Connect2Connectors)
372
                        {
373
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
374
                            {
375
                                endClearModelItemID.Add(connector.ModelItemID);
376
                                LMModelItem modelItem = connector.ModelItemObject;
377
                                if (modelItem != null)
378
                                {
379
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
380
                                    if (attribute != null)
381
                                        attribute.set_Value(DBNull.Value);
382

    
383
                                    modelItem.Commit();
384
                                    ReleaseCOMObjects(modelItem);
385
                                    modelItem = null;
386
                                }
387
                            }
388
                        }
389
                    }
390
                    ReleaseCOMObjects(symbol);
391
                    symbol = null;
392
                }
393
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
394
            }
395
        }
396
        private void RunClearValueInconsistancy()
397
        {
398
            int count = 1;
399
            bool loop = true;
400
            while (loop)
401
            {
402
                loop = false;
403
                LMAFilter filter = new LMAFilter();
404
                LMACriterion criterion = new LMACriterion();
405
                filter.ItemType = "Relationship";
406
                criterion.SourceAttributeName = "SP_DRAWINGID";
407
                criterion.Operator = "=";
408
                criterion.set_ValueAttribute(drawingID);
409
                filter.get_Criteria().Add(criterion);
410

    
411
                LMRelationships relationships = new LMRelationships();
412
                relationships.Collect(dataSource, Filter: filter);
413

    
414
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
415
                if (count > 1)
416
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
417
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
418
                foreach (LMRelationship relationship in relationships)
419
                {
420
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
421
                    {
422
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
423
                        {
424
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
425
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
426
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
427
                            if (modelItem1 != null)
428
                            {
429
                                string attrName = array[0];
430
                                if (attrName.Contains("PipingPoint"))
431
                                {
432
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
433
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
434
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
435
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
436
                                    {
437
                                        loop = true;
438
                                        attribute1.set_Value(DBNull.Value);
439
                                    }
440
                                    attribute1 = null;
441
                                }
442
                                else
443
                                {
444
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
445
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
446
                                    {
447
                                        loop = true;
448
                                        attribute1.set_Value(DBNull.Value);
449
                                    }
450
                                    attribute1 = null;
451
                                }
452
                                modelItem1.Commit();
453
                            }
454
                            if (modelItem2 != null)
455
                            {
456
                                string attrName = array[1];
457
                                if (attrName.Contains("PipingPoint"))
458
                                {
459
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
460
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
461
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
462
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
463
                                    {
464
                                        attribute2.set_Value(DBNull.Value);
465
                                        loop = true;
466
                                    }
467
                                    attribute2 = null;
468
                                }
469
                                else
470
                                {
471
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
472
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
473
                                    {
474
                                        attribute2.set_Value(DBNull.Value);
475
                                        loop = true;
476
                                    }
477
                                    attribute2 = null;
478
                                }
479
                                modelItem2.Commit();
480
                            }
481
                            ReleaseCOMObjects(modelItem1);
482
                            modelItem1 = null;
483
                            ReleaseCOMObjects(modelItem2);
484
                            modelItem2 = null;
485
                            inconsistency.Commit();
486
                        }
487
                        ReleaseCOMObjects(inconsistency);
488
                    }
489
                    relationship.Commit();
490
                    ReleaseCOMObjects(relationship);
491
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
492
                }
493
                ReleaseCOMObjects(filter);
494
                filter = null;
495
                ReleaseCOMObjects(criterion);
496
                criterion = null;
497
                ReleaseCOMObjects(relationships);
498
                relationships = null;
499
                count++;
500
            }
501
        }
502
        private void RunEndBreakModeling()
503
        {
504
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
505
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
506
            foreach (var item in document.EndBreaks)
507
                try
508
                {
509
                    EndBreakModeling(item);
510
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
511
                }
512
                catch (Exception ex)
513
                {
514
                    Log.Write("Error in EndBreakModeling");
515
                    Log.Write("UID : " + item.UID);
516
                    Log.Write(ex.Message);
517
                    Log.Write(ex.StackTrace);
518
                }
519
        }
520
        private void RunSpecBreakModeling()
521
        {
522
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
523
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
524
            foreach (var item in document.SpecBreaks)
525
                try
526
                {
527
                    SpecBreakModeling(item);
528
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
529
                }
530
                catch (Exception ex)
531
                {
532
                    Log.Write("Error in SpecBreakModeling");
533
                    Log.Write("UID : " + item.UID);
534
                    Log.Write(ex.Message);
535
                    Log.Write(ex.StackTrace);
536
                }
537
        }
538
        private void RunJoinRunForSameConnector()
539
        {
540
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
541
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
542
            foreach (var line in document.LINES)
543
            {
544
                Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(line.SPPID.ModelItemId, false);
545
                List<List<double[]>> result = new List<List<double[]>>();
546
                foreach (var item in vertices)
547
                {
548
                    ReleaseCOMObjects(item.Key);
549
                    result.Add(item.Value);
550
                }
551
                line.SPPID.Vertices = result;
552
                vertices = null;
553
            }
554

    
555
            foreach (var line in document.LINES)
556
            {
557
                foreach (var connector in line.CONNECTORS)
558
                {
559
                    if (connector.ConnectedObject != null &&
560
                        connector.ConnectedObject.GetType() == typeof(Line) &&
561
                        !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
562
                    {
563
                        Line connLine = connector.ConnectedObject as Line;
564
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
565
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
566
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
567
                            !SPPIDUtil.IsSegment(document, line, connLine))
568
                        {
569
                            string survivorId = string.Empty;
570
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
571
                        }
572

    
573
                    }
574
                }
575
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
576
            }
577

    
578
            foreach (var line in document.LINES)
579
                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
580
        }
581
        private void RunJoinRun()
582
        {
583
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
584
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
585
            List<string> endModelID = new List<string>();
586
            foreach (var line in document.LINES)
587
            {
588
                if (!endModelID.Contains(line.SPPID.ModelItemId))
589
                {
590
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
591
                    {
592
                        string survivorId = string.Empty;
593
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
594
                        if (string.IsNullOrEmpty(survivorId))
595
                        {
596
                            endModelID.Add(line.SPPID.ModelItemId);
597
                        }
598
                    }
599
                }
600
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
601
            }
602
        }
603
        private void RunLineNumberModeling()
604
        {
605
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
606
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
607
            foreach (var item in document.LINENUMBERS)
608
            {
609
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
610
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
611
                {
612
                    ReleaseCOMObjects(label);
613
                    item.SPPID.RepresentationId = null;
614
                    LineNumberModeling(item);
615
                }
616
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
617
            }
618
        }
619
        private void RunFlowDirection()
620
        {
621
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, 
622
                document.LINES.Count + ZeroLengthModelItemID.Count + ZeroLengthModelItemIDReverse.Count + ZeroLengthSymbolToSymbolModelItemID.Count);
623
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Check Flow Direction");
624
            foreach (var line in document.LINES)
625
            {
626
                if (!string.IsNullOrEmpty(line.SPPID.ModelItemId))
627
                {
628
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
629
                    if (modelItem != null && modelItem.get_ItemStatus() == "Active")
630
                    {
631
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
632
                        if (attribute != null)
633
                        {
634
                            attribute.set_Value("End 1 is upstream (Inlet)");
635
                            modelItem.Commit();
636
                        }
637

    
638
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
639

    
640
                        ReleaseCOMObjects(modelItem);
641
                        modelItem = null;
642
                    }
643
                }
644

    
645
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
646
            }
647
            foreach (var modelId in ZeroLengthModelItemID)
648
            {
649
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
650
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
651
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
652
                {
653
                    attribute.set_Value("End 1 is upstream (Inlet)");
654
                    zeroLengthModelItem.Commit();
655
                }
656

    
657
                SetFlowDirectionByLine(modelId);
658

    
659
                ReleaseCOMObjects(zeroLengthModelItem);
660
                zeroLengthModelItem = null;
661

    
662
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
663
            }
664
            foreach (var modelId in ZeroLengthModelItemIDReverse)
665
            {
666
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
667
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
668
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
669
                {
670
                    attribute.set_Value("End 1 is downstream (Outlet)");
671
                    zeroLengthModelItem.Commit();
672
                }
673

    
674
                SetFlowDirectionByLine(modelId);
675

    
676
                ReleaseCOMObjects(zeroLengthModelItem);
677
                zeroLengthModelItem = null;
678

    
679
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
680
            }
681
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
682
            {
683
                SetFlowDirectionByLine(modelId);
684
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
685
            }
686

    
687
            void SetFlowDirectionByLine(string lineModelItemID)
688
            {
689
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
690
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
691
                {
692
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
693
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
694
                    {
695
                        string sFlowDirection = attribute.get_Value().ToString();
696
                        foreach (LMRepresentation rep in modelItem.Representations)
697
                        {
698
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
699
                            {
700
                                LMConnector connector = dataSource.GetConnector(rep.Id);
701

    
702
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
703
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
704
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
705
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
706

    
707
                                ReleaseCOMObjects(connector);
708
                            }
709
                        }
710
                    }
711
                    ReleaseCOMObjects(modelItem);
712
                    modelItem = null;
713
                }
714

    
715
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
716
                {
717
                    // Item2가 Symbol
718
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
719
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
720
                    {
721
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
722
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
723
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
724

    
725
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
726

    
727
                        symbolModelItem.Commit();
728
                        ReleaseCOMObjects(symbolModelItem);
729
                        symbolModelItem = null;
730
                    }
731
                    // Item1이 Symbol
732
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
733
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
734
                    {
735
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
736
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
737
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
738

    
739
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
740

    
741
                        symbolModelItem.Commit();
742
                        ReleaseCOMObjects(symbolModelItem);
743
                        symbolModelItem = null;
744
                    }
745
                }
746

    
747
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
748
                {
749
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
750
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
751
                    if (attribute != null)
752
                    {
753
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
754
                            attribute.set_Value("End 1 is downstream (Outlet)");
755
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
756
                            attribute.set_Value("End 1 is upstream (Inlet)");
757
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
758
                            attribute.set_Value("End 1 is upstream (Inlet)");
759
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
760
                            attribute.set_Value("End 1 is downstream (Outlet)");
761
                    }
762
                }
763
            }
764
        }
765
        private void RunNoteModeling()
766
        {
767
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
768
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
769
            List<Note> correctList = new List<Note>();
770
            foreach (var item in document.NOTES)
771
                try
772
                {
773
                    NoteModeling(item, correctList);
774
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
775
                }
776
                catch (Exception ex)
777
                {
778
                    Log.Write("Error in NoteModeling");
779
                    Log.Write("UID : " + item.UID);
780
                    Log.Write(ex.Message);
781
                    Log.Write(ex.StackTrace);
782
                }
783

    
784
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
785
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
786
            SortNote(correctList);
787
            List<Note> endList = new List<Note>();
788
            if (correctList.Count > 0)
789
                endList.Add(correctList[0]);
790
            foreach (var item in correctList)
791
                try
792
                {
793
                    if (!endList.Contains(item))
794
                        NoteCorrectModeling(item, endList);
795
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
796
                }
797
                catch (Exception ex)
798
                {
799
                    Log.Write("Error in NoteModeling");
800
                    Log.Write("UID : " + item.UID);
801
                    Log.Write(ex.Message);
802
                    Log.Write(ex.StackTrace);
803
                }
804
        }
805
        private void RunTextModeling()
806
        {
807
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
808
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
809
            SortText(document.TEXTINFOS);
810
            foreach (var item in document.TEXTINFOS)
811
                try
812
                {
813
                    if (item.ASSOCIATION)
814
                        AssociationTextModeling(item);
815
                    else
816
                        NormalTextModeling(item);
817
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
818
                }
819
                catch (Exception ex)
820
                {
821
                    Log.Write("Error in TextModeling");
822
                    Log.Write("UID : " + item.UID);
823
                    Log.Write(ex.Message);
824
                    Log.Write(ex.StackTrace);
825
                }
826
        }
827
        private void RunInputLineNumberAttribute()
828
        {
829
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
830
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
831
            List<string> endLine = new List<string>();
832
            foreach (var item in document.LINENUMBERS)
833
                try
834
                {
835
                    InputLineNumberAttribute(item, endLine);
836
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
837
                }
838
                catch (Exception ex)
839
                {
840
                    Log.Write("Error in InputLineNumberAttribute");
841
                    Log.Write("UID : " + item.UID);
842
                    Log.Write(ex.Message);
843
                    Log.Write(ex.StackTrace);
844
                }
845
        }
846
        private void RunInputSymbolAttribute()
847
        {
848
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
849
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
850
            foreach (var item in document.SYMBOLS)
851
                try
852
                {
853
                    InputSymbolAttribute(item, item.ATTRIBUTES);
854
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
855
                }
856
                catch (Exception ex)
857
                {
858
                    Log.Write("Error in InputSymbolAttribute");
859
                    Log.Write("UID : " + item.UID);
860
                    Log.Write(ex.Message);
861
                    Log.Write(ex.StackTrace);
862
                }
863
        }
864
        private void RunInputSpecBreakAttribute()
865
        {
866
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
867
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
868
            foreach (var item in document.SpecBreaks)
869
                try
870
                {
871
                    InputSpecBreakAttribute(item);
872
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
873
                }
874
                catch (Exception ex)
875
                {
876
                    Log.Write("Error in InputSpecBreakAttribute");
877
                    Log.Write("UID : " + item.UID);
878
                    Log.Write(ex.Message);
879
                    Log.Write(ex.StackTrace);
880
                }
881
        }
882
        private void RunInputEndBreakAttribute()
883
        {
884
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
885
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
886
            foreach (var item in document.EndBreaks)
887
                try
888
                {
889
                    InputEndBreakAttribute(item);
890
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
891
                }
892
                catch (Exception ex)
893
                {
894
                    Log.Write("Error in RunInputEndBreakAttribute");
895
                    Log.Write("UID : " + item.UID);
896
                    Log.Write(ex.Message);
897
                    Log.Write(ex.StackTrace);
898
                }
899
        }
900
        private void RunLabelSymbolModeling()
901
        {
902
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
903
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
904
            foreach (var item in document.SYMBOLS)
905
                try
906
                {
907
                    LabelSymbolModeling(item);
908
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
909
                }
910
                catch (Exception ex)
911
                {
912
                    Log.Write("Error in LabelSymbolModeling");
913
                    Log.Write("UID : " + item.UID);
914
                    Log.Write(ex.Message);
915
                    Log.Write(ex.StackTrace);
916
                }
917
        }
918
        private void RunCorrectAssociationText()
919
        {
920
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
921
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
922
            List<Text> endTexts = new List<Text>();
923
            foreach (var item in document.TEXTINFOS)
924
            {
925
                try
926
                {
927
                    if (item.ASSOCIATION && !endTexts.Contains(item))
928
                        AssociationTextCorrectModeling(item, endTexts);
929
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
930
                }
931
                catch (Exception ex)
932
                {
933
                    Log.Write("Error in RunCorrectAssociationText");
934
                    Log.Write("UID : " + item.UID);
935
                    Log.Write(ex.Message);
936
                    Log.Write(ex.StackTrace);
937
                }
938
                
939
            }
940

    
941
            foreach (var item in document.LINENUMBERS)
942
            {
943
                try
944
                {
945
                    LineNumberCorrectModeling(item);
946
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
947
                }
948
                catch (Exception ex)
949
                {
950
                    Log.Write("Error in RunCorrectAssociationText");
951
                    Log.Write("UID : " + item.UID);
952
                    Log.Write(ex.Message);
953
                    Log.Write(ex.StackTrace);
954
                }
955
            }
956
        }
957
        /// <summary>
958
        /// 도면 생성 메서드
959
        /// </summary>
960
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
961
        {
962
            Log.Write("------------------ Start create document ------------------");
963
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
964
            Log.Write("Drawing name : " + drawingName);
965
            Log.Write("Drawing number : " + drawingNumber);
966
            Thread.Sleep(1000);
967
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
968
            if (newDrawing != null)
969
            {
970
                document.SPPID_DrawingNumber = drawingNumber;
971
                document.SPPID_DrawingName = drawingName;
972
                Thread.Sleep(1000);
973
                radApp.ActiveWindow.Fit();
974
                Thread.Sleep(1000);
975
                radApp.ActiveWindow.Zoom = 2000;
976
                Thread.Sleep(2000);
977

    
978
                //current LMDrawing 가져오기
979
                LMAFilter filter = new LMAFilter();
980
                LMACriterion criterion = new LMACriterion();
981
                filter.ItemType = "Drawing";
982
                criterion.SourceAttributeName = "Name";
983
                criterion.Operator = "=";
984
                criterion.set_ValueAttribute(drawingName);
985
                filter.get_Criteria().Add(criterion);
986

    
987
                LMDrawings drawings = new LMDrawings();
988
                drawings.Collect(dataSource, Filter: filter);
989

    
990
                drawingID = ((dynamic)drawings).Nth(1).Id;
991
                ReleaseCOMObjects(filter);
992
                ReleaseCOMObjects(criterion);
993
                ReleaseCOMObjects(drawings);
994
                filter = null;
995
                criterion = null;
996
                drawings = null;
997
            }
998
            else
999
                Log.Write("Fail Create Drawing");
1000

    
1001
            if (newDrawing != null)
1002
                return true;
1003
            else
1004
                return false;
1005
        }
1006

    
1007
        /// <summary>
1008
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1009
        /// </summary>
1010
        /// <param name="drawingName"></param>
1011
        /// <param name="drawingNumber"></param>
1012
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1013
        {
1014
            LMDrawings drawings = new LMDrawings();
1015
            drawings.Collect(dataSource);
1016

    
1017
            List<string> drawingNameList = new List<string>();
1018
            List<string> drawingNumberList = new List<string>();
1019

    
1020
            foreach (LMDrawing item in drawings)
1021
            {
1022
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1023
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1024
            }
1025

    
1026
            int nameLength = drawingName.Length;
1027
            while (drawingNameList.Contains(drawingName))
1028
            {
1029
                if (nameLength == drawingName.Length)
1030
                    drawingName += "-1";
1031
                else
1032
                {
1033
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1034
                    drawingName = drawingName.Substring(0, nameLength + 1);
1035
                    drawingName += ++index;
1036
                }
1037
            }
1038

    
1039
            int numberLength = drawingNumber.Length;
1040
            while (drawingNameList.Contains(drawingNumber))
1041
            {
1042
                if (numberLength == drawingNumber.Length)
1043
                    drawingNumber += "-1";
1044
                else
1045
                {
1046
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1047
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1048
                    drawingNumber += ++index;
1049
                }
1050
            }
1051
            ReleaseCOMObjects(drawings);
1052
            drawings = null;
1053
        }
1054

    
1055
        /// <summary>
1056
        /// 도면 크기 구하는 메서드
1057
        /// </summary>
1058
        /// <returns></returns>
1059
        private bool DocumentCoordinateCorrection()
1060
        {
1061
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1062
            {
1063
                Log.Write("Setting Drawing X, Drawing Y");
1064
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1065
                Log.Write("Start coordinate correction");
1066
                document.CoordinateCorrection();
1067
                return true;
1068
            }
1069
            else
1070
            {
1071
                Log.Write("Need Drawing X, Y");
1072
                return false;
1073
            }
1074
        }
1075

    
1076
        /// <summary>
1077
        /// 심볼을 실제로 Modeling 메서드
1078
        /// </summary>
1079
        /// <param name="symbol">생성할 심볼</param>
1080
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1081
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1082
        {
1083
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1084
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1085
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1086
                return;
1087
            // 이미 모델링 됐을 경우
1088
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1089
                return;
1090

    
1091
            LMSymbol _LMSymbol = null;
1092

    
1093
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1094
            double x = symbol.SPPID.ORIGINAL_X;
1095
            double y = symbol.SPPID.ORIGINAL_Y;
1096
            int mirror = 0;
1097
            double angle = symbol.ANGLE;
1098

    
1099
            // OPC 일경우 180도 일때 Mirror
1100
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1101
                mirror = 1;
1102

    
1103
            // Mirror 계산
1104
            if (symbol.FLIP == 1)
1105
            {
1106
                mirror = 1;
1107
                angle += Math.PI;
1108
            }
1109

    
1110
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1111
            {
1112
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1113
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1114
                if (connector != null)
1115
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1116

    
1117
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1118
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1119
                if (temp != null)
1120
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1121
                ReleaseCOMObjects(temp);
1122
                temp = null;
1123

    
1124
                if (_LMSymbol != null && _TargetItem != null)
1125
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1126

    
1127
                ReleaseCOMObjects(_TargetItem);
1128
            }
1129
            else
1130
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1131

    
1132
            if (_LMSymbol != null)
1133
            {
1134
                _LMSymbol.Commit();
1135

    
1136
                // ConnCheck
1137
                List<string> ids = new List<string>();
1138
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1139
                {
1140
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1141
                        ids.Add(item.Id);
1142
                    ReleaseCOMObjects(item);
1143
                }
1144
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1145
                {
1146
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1147
                        ids.Add(item.Id);
1148
                    ReleaseCOMObjects(item);
1149
                }
1150

    
1151
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1152
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1153
                {
1154
                    double currentX = _LMSymbol.get_XCoordinate();
1155
                    double currentY = _LMSymbol.get_YCoordinate();
1156

    
1157

    
1158
                }
1159

    
1160
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1161
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1162
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1163

    
1164
                foreach (var item in symbol.ChildSymbols)
1165
                    CreateChildSymbol(item, _LMSymbol, symbol);
1166

    
1167
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1168
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1169

    
1170
                double[] range = null;
1171
                GetSPPIDSymbolRange(symbol, ref range);
1172
                symbol.SPPID.SPPID_Min_X = range[0];
1173
                symbol.SPPID.SPPID_Min_Y = range[1];
1174
                symbol.SPPID.SPPID_Max_X = range[2];
1175
                symbol.SPPID.SPPID_Max_Y = range[3];
1176

    
1177
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1178
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1179
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1180
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1181

    
1182
                ReleaseCOMObjects(_LMSymbol);
1183
            }
1184
        }
1185
        /// <summary>
1186
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1187
        /// Signal Point는 고려하지 않음
1188
        /// </summary>
1189
        /// <param name="symbol"></param>
1190
        /// <param name="_TargetItem"></param>
1191
        /// <param name="targetX"></param>
1192
        /// <param name="targetY"></param>
1193
        /// <returns></returns>
1194
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1195
        {
1196
            LMConnector tempConnector = null;
1197

    
1198
            List<Symbol> group = new List<Symbol>();
1199
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1200
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1201
            {
1202
                List<Connector> connectors = new List<Connector>();
1203
                foreach (var item in group)
1204
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1205
                /// Primary or Secondary Type Line만 고려
1206
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1207
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1208
                if (_connector != null)
1209
                {
1210
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1211
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1212
                    /// PipingPoint가 2개 이상만
1213
                    if (pointInfos.Count >= 2)
1214
                    {
1215
                        double lineX = 0;
1216
                        double lineY = 0;
1217
                        double length = 0;
1218
                        foreach (var item in pointInfos)
1219
                        {
1220
                            double tempX = item[1];
1221
                            double tempY = item[2];
1222

    
1223
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1224
                            if (calcDistance > length)
1225
                            {
1226
                                lineX = tempX;
1227
                                lineY = tempY;
1228
                            }
1229
                        }
1230

    
1231
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1232
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1233
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1234
                        placeRunInputs.AddPoint(-1, -1);
1235
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1236
                        if (tempConnector != null)
1237
                            tempConnector.Commit();
1238
                        ReleaseCOMObjects(_LMAItem);
1239
                        _LMAItem = null;
1240
                        ReleaseCOMObjects(placeRunInputs);
1241
                        placeRunInputs = null;
1242
                    }
1243
                }
1244
            }
1245

    
1246
            return tempConnector;
1247
        }
1248
        /// <summary>
1249
        /// Symbol의 PipingPoints를 구함
1250
        /// SignalPoint는 고려하지 않음
1251
        /// </summary>
1252
        /// <param name="symbol"></param>
1253
        /// <returns></returns>
1254
        private List<double[]> getPipingPoints(LMSymbol symbol)
1255
        {
1256
            LMModelItem modelItem = symbol.ModelItemObject;
1257
            LMPipingPoints pipingPoints = null;
1258
            if (modelItem.get_ItemTypeName() == "PipingComp")
1259
            {
1260
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1261
                pipingPoints = pipingComp.PipingPoints;
1262
                ReleaseCOMObjects(pipingComp);
1263
                pipingComp = null;
1264
            }
1265
            else if (modelItem.get_ItemTypeName() == "Instrument")
1266
            {
1267
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1268
                pipingPoints = instrument.PipingPoints;
1269
                ReleaseCOMObjects(instrument);
1270
                instrument = null;
1271
            }
1272
            else
1273
                Log.Write("다른 Type");
1274

    
1275
            List<double[]> info = new List<double[]>();
1276
            if (pipingPoints != null)
1277
            {
1278
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1279
                {
1280
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1281
                    {
1282
                        if (attribute.Name == "PipingPointNumber")
1283
                        {
1284
                            int index = Convert.ToInt32(attribute.get_Value());
1285
                            if (info.Find(loopX => loopX[0] == index) == null)
1286
                            {
1287
                                double x = 0;
1288
                                double y = 0;
1289
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1290
                                    info.Add(new double[] { index, x, y });
1291
                            }
1292
                        }
1293
                    }
1294
                }
1295
            }
1296
            ReleaseCOMObjects(modelItem);
1297
            modelItem = null;
1298
            ReleaseCOMObjects(pipingPoints);
1299
            pipingPoints = null;
1300

    
1301
            return info;
1302
        }
1303

    
1304
        private void RemoveSymbol(Symbol symbol)
1305
        {
1306
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1307
            {
1308
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1309
                if (_LMSymbol != null)
1310
                {
1311
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1312
                    ReleaseCOMObjects(_LMSymbol);
1313
                }
1314
            }
1315

    
1316
            symbol.SPPID.RepresentationId = string.Empty;
1317
            symbol.SPPID.ModelItemID = string.Empty;
1318
            symbol.SPPID.SPPID_X = double.NaN;
1319
            symbol.SPPID.SPPID_Y = double.NaN;
1320
            symbol.SPPID.SPPID_Min_X = double.NaN;
1321
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1322
            symbol.SPPID.SPPID_Max_X = double.NaN;
1323
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1324
        }
1325

    
1326
        private void RemoveSymbol(List<Symbol> symbols)
1327
        {
1328
            foreach (var symbol in symbols)
1329
            {
1330
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1331
                {
1332
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1333
                    if (_LMSymbol != null)
1334
                    {
1335
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1336
                        ReleaseCOMObjects(_LMSymbol);
1337
                    }
1338
                }
1339

    
1340
                symbol.SPPID.RepresentationId = string.Empty;
1341
                symbol.SPPID.ModelItemID = string.Empty;
1342
                symbol.SPPID.SPPID_X = double.NaN;
1343
                symbol.SPPID.SPPID_Y = double.NaN;
1344
                symbol.SPPID.SPPID_Min_X = double.NaN;
1345
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1346
                symbol.SPPID.SPPID_Max_X = double.NaN;
1347
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1348
            }
1349
        }
1350

    
1351
        /// <summary>
1352
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1353
        /// </summary>
1354
        /// <param name="targetConnector"></param>
1355
        /// <param name="targetSymbol"></param>
1356
        /// <param name="x"></param>
1357
        /// <param name="y"></param>
1358
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1359
        {
1360
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1361

    
1362
            double[] range = null;
1363
            List<double[]> points = new List<double[]>();
1364
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1365
            double x1 = range[0];
1366
            double y1 = range[1];
1367
            double x2 = range[2];
1368
            double y2 = range[3];
1369

    
1370
            // Origin 기준 Connector의 위치차이
1371
            double sceneX = 0;
1372
            double sceneY = 0;
1373
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1374
            double originX = 0;
1375
            double originY = 0;
1376
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1377
            double gapX = originX - sceneX;
1378
            double gapY = originY - sceneY;
1379

    
1380
            // SPPID Symbol과 ID2 심볼의 크기 차이
1381
            double sizeWidth = 0;
1382
            double sizeHeight = 0;
1383
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1384
            if (sizeWidth == 0 || sizeHeight == 0)
1385
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1386

    
1387
            double percentX = (x2 - x1) / sizeWidth;
1388
            double percentY = (y2 - y1) / sizeHeight;
1389

    
1390
            double SPPIDgapX = gapX * percentX;
1391
            double SPPIDgapY = gapY * percentY;
1392

    
1393
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1394
            double distance = double.MaxValue;
1395
            double[] resultPoint;
1396
            foreach (var point in points)
1397
            {
1398
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1399
                if (distance > result)
1400
                {
1401
                    distance = result;
1402
                    resultPoint = point;
1403
                    x = point[0];
1404
                    y = point[1];
1405
                }
1406
            }
1407

    
1408
            ReleaseCOMObjects(_TargetItem);
1409
        }
1410

    
1411
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1412
        {
1413
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1414
            if (index == 0)
1415
            {
1416
                x = targetLine.SPPID.START_X;
1417
                y = targetLine.SPPID.START_Y;
1418
            }
1419
            else
1420
            {
1421
                x = targetLine.SPPID.END_X;
1422
                y = targetLine.SPPID.END_Y;
1423
            }
1424
        }
1425

    
1426
        /// <summary>
1427
        /// SPPID Symbol의 Range를 구한다.
1428
        /// </summary>
1429
        /// <param name="symbol"></param>
1430
        /// <param name="range"></param>
1431
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1432
        {
1433
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1434
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1435
            double x1 = 0;
1436
            double y1 = 0;
1437
            double x2 = 0;
1438
            double y2 = 0;
1439
            symbol2d.Range(out x1, out y1, out x2, out y2);
1440
            range = new double[] { x1, y1, x2, y2 };
1441

    
1442
            for (int i = 1; i < int.MaxValue; i++)
1443
            {
1444
                double connX = 0;
1445
                double connY = 0;
1446
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1447
                    points.Add(new double[] { connX, connY });
1448
                else
1449
                    break;
1450
            }
1451

    
1452
            foreach (var childSymbol in symbol.ChildSymbols)
1453
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1454

    
1455
            ReleaseCOMObjects(_TargetItem);
1456
        }
1457

    
1458
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1459
        {
1460
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1461
            if (_TargetItem != null)
1462
            {
1463
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1464
                double x1 = 0;
1465
                double y1 = 0;
1466
                double x2 = 0;
1467
                double y2 = 0;
1468
                if (!bForGraphic)
1469
                {
1470
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1471
                    range = new double[] { x1, y1, x2, y2 };
1472
                }
1473
                else
1474
                {
1475
                    x1 = double.MaxValue;
1476
                    y1 = double.MaxValue;
1477
                    x2 = double.MinValue;
1478
                    y2 = double.MinValue;
1479
                    range = new double[] { x1, y1, x2, y2 };
1480

    
1481
                    foreach (var item in symbol2d.DrawingObjects)
1482
                    {
1483
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1484
                        {
1485
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1486
                            if (rangeObject.Layer == "Default")
1487
                            {
1488
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1489
                                range = new double[] {
1490
                                Math.Min(x1, range[0]),
1491
                                Math.Min(y1, range[1]),
1492
                                Math.Max(x2, range[2]),
1493
                                Math.Max(y2, range[3])
1494
                            };
1495
                            }
1496
                        }
1497
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1498
                        {
1499
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1500
                            if (rangeObject.Layer == "Default")
1501
                            {
1502
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1503
                                range = new double[] {
1504
                                Math.Min(x1, range[0]),
1505
                                Math.Min(y1, range[1]),
1506
                                Math.Max(x2, range[2]),
1507
                                Math.Max(y2, range[3])
1508
                            };
1509
                            }
1510
                        }
1511
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1512
                        {
1513
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1514
                            if (rangeObject.Layer == "Default")
1515
                            {
1516
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1517
                                range = new double[] {
1518
                                Math.Min(x1, range[0]),
1519
                                Math.Min(y1, range[1]),
1520
                                Math.Max(x2, range[2]),
1521
                                Math.Max(y2, range[3])
1522
                            };
1523
                            }
1524
                        }
1525
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1526
                        {
1527
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1528
                            if (rangeObject.Layer == "Default")
1529
                            {
1530
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1531
                                range = new double[] {
1532
                                Math.Min(x1, range[0]),
1533
                                Math.Min(y1, range[1]),
1534
                                Math.Max(x2, range[2]),
1535
                                Math.Max(y2, range[3])
1536
                            };
1537
                            }
1538
                        }
1539
                    }
1540
                }
1541

    
1542
                if (!bOnlySymbol)
1543
                {
1544
                    foreach (var childSymbol in symbol.ChildSymbols)
1545
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1546
                }
1547
                ReleaseCOMObjects(_TargetItem);
1548
            }
1549
        }
1550

    
1551
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1552
        {
1553
            if (labelPersist != null)
1554
            {
1555
                double x1 = double.MaxValue;
1556
                double y1 = double.MaxValue;
1557
                double x2 = double.MinValue;
1558
                double y2 = double.MinValue;
1559
                range = new double[] { x1, y1, x2, y2 };
1560

    
1561
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1562
                foreach (var item in dependency.DrawingObjects)
1563
                {
1564
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1565
                    if (textBox != null)
1566
                    {
1567
                        if (dependency != null)
1568
                        {
1569
                            double tempX1;
1570
                            double tempY1;
1571
                            double tempX2;
1572
                            double tempY2;
1573
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1574
                            x1 = Math.Min(x1, tempX1);
1575
                            y1 = Math.Min(y1, tempY1);
1576
                            x2 = Math.Max(x2, tempX2);
1577
                            y2 = Math.Max(y2, tempY2);
1578

    
1579
                            range = new double[] { x1, y1, x2, y2 };
1580
                        }
1581
                    }
1582
                }
1583
                
1584
            }
1585
        }
1586

    
1587
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1588
        {
1589
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1590
            foreach (var symbol in symbols)
1591
            {
1592
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1593
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1594
                double x1 = 0;
1595
                double y1 = 0;
1596
                double x2 = 0;
1597
                double y2 = 0;
1598
                symbol2d.Range(out x1, out y1, out x2, out y2);
1599

    
1600
                tempRange[0] = Math.Min(tempRange[0], x1);
1601
                tempRange[1] = Math.Min(tempRange[1], y1);
1602
                tempRange[2] = Math.Max(tempRange[2], x2);
1603
                tempRange[3] = Math.Max(tempRange[3], y2);
1604

    
1605
                foreach (var childSymbol in symbol.ChildSymbols)
1606
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1607

    
1608
                ReleaseCOMObjects(_TargetItem);
1609
            }
1610

    
1611
            range = tempRange;
1612
        }
1613

    
1614
        /// <summary>
1615
        /// Child Modeling 된 Symbol의 Range를 구한다.
1616
        /// </summary>
1617
        /// <param name="childSymbol"></param>
1618
        /// <param name="range"></param>
1619
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1620
        {
1621
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1622
            if (_ChildSymbol != null)
1623
            {
1624
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1625
                double x1 = 0;
1626
                double y1 = 0;
1627
                double x2 = 0;
1628
                double y2 = 0;
1629
                symbol2d.Range(out x1, out y1, out x2, out y2);
1630
                range[0] = Math.Min(range[0], x1);
1631
                range[1] = Math.Min(range[1], y1);
1632
                range[2] = Math.Max(range[2], x2);
1633
                range[3] = Math.Max(range[3], y2);
1634

    
1635
                for (int i = 1; i < int.MaxValue; i++)
1636
                {
1637
                    double connX = 0;
1638
                    double connY = 0;
1639
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1640
                        points.Add(new double[] { connX, connY });
1641
                    else
1642
                        break;
1643
                }
1644

    
1645
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1646
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1647

    
1648
                ReleaseCOMObjects(_ChildSymbol);
1649
            }
1650
        }
1651

    
1652
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1653
        {
1654
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1655
            if (_ChildSymbol != null)
1656
            {
1657
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1658
                double x1 = 0;
1659
                double y1 = 0;
1660
                double x2 = 0;
1661
                double y2 = 0;
1662
                symbol2d.Range(out x1, out y1, out x2, out y2);
1663
                range[0] = Math.Min(range[0], x1);
1664
                range[1] = Math.Min(range[1], y1);
1665
                range[2] = Math.Max(range[2], x2);
1666
                range[3] = Math.Max(range[3], y2);
1667

    
1668
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1669
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1670
                ReleaseCOMObjects(_ChildSymbol);
1671
            }
1672
        }
1673

    
1674
        /// <summary>
1675
        /// Label Symbol Modeling
1676
        /// </summary>
1677
        /// <param name="symbol"></param>
1678
        private void LabelSymbolModeling(Symbol symbol)
1679
        {
1680
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1681
            {
1682
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1683
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1684
                    return;
1685
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1686

    
1687
                string symbolUID = itemAttribute.VALUE;
1688
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1689
                if (targetItem != null &&
1690
                    (targetItem.GetType() == typeof(Symbol) ||
1691
                    targetItem.GetType() == typeof(Equipment)))
1692
                {
1693
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1694
                    string sRep = null;
1695
                    if (targetItem.GetType() == typeof(Symbol))
1696
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1697
                    else if (targetItem.GetType() == typeof(Equipment))
1698
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1699
                    if (!string.IsNullOrEmpty(sRep))
1700
                    {
1701
                        // LEADER Line 검사
1702
                        bool leaderLine = false;
1703
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1704
                        if (symbolMapping != null)
1705
                            leaderLine = symbolMapping.LEADERLINE;
1706

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

    
1711
                        //Leader 선 센터로
1712
                        if (_LMLabelPresist != null)
1713
                        {
1714
                            // Target Item에 Label의 Attribute Input
1715
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1716

    
1717
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1718
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1719
                            if (dependency != null)
1720
                            {
1721
                                bool result = false;
1722
                                foreach (var attributes in dependency.AttributeSets)
1723
                                {
1724
                                    foreach (var attribute in attributes)
1725
                                    {
1726
                                        string name = attribute.Name;
1727
                                        string value = attribute.GetValue().ToString();
1728
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1729
                                        {
1730
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1731
                                            {
1732
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1733
                                                {
1734
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1735
                                                    double prevX = _TargetItem.get_XCoordinate();
1736
                                                    double prevY = _TargetItem.get_YCoordinate();
1737
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1738
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1739
                                                    result = true;
1740
                                                    break;
1741
                                                }
1742
                                            }
1743
                                        }
1744

    
1745
                                        if (result)
1746
                                            break;
1747
                                    }
1748

    
1749
                                    if (result)
1750
                                        break;
1751
                                }
1752
                            }
1753

    
1754
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1755
                            _LMLabelPresist.Commit();
1756
                            ReleaseCOMObjects(_LMLabelPresist);
1757
                        }
1758

    
1759
                        ReleaseCOMObjects(_TargetItem);
1760
                    }
1761
                }
1762
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1763
                {
1764
                    Line targetLine = targetItem as Line;
1765
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1766
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1767
                    if (connectedLMConnector != null)
1768
                    {
1769
                        // LEADER Line 검사
1770
                        bool leaderLine = false;
1771
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1772
                        if (symbolMapping != null)
1773
                            leaderLine = symbolMapping.LEADERLINE;
1774

    
1775
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1776
                        if (_LMLabelPresist != null)
1777
                        {
1778
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1779
                            _LMLabelPresist.Commit();
1780
                            ReleaseCOMObjects(_LMLabelPresist);
1781
                        }
1782
                        ReleaseCOMObjects(connectedLMConnector);
1783
                    }
1784

    
1785
                    foreach (var item in connectorVertices)
1786
                        if (item.Key != null)
1787
                            ReleaseCOMObjects(item.Key);
1788
                }
1789
            }
1790
        }
1791

    
1792
        /// <summary>
1793
        /// Equipment를 실제로 Modeling 메서드
1794
        /// </summary>
1795
        /// <param name="equipment"></param>
1796
        private void EquipmentModeling(Equipment equipment)
1797
        {
1798
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1799
                return;
1800

    
1801
            LMSymbol _LMSymbol = null;
1802
            LMSymbol targetItem = null;
1803
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1804
            double x = equipment.SPPID.ORIGINAL_X;
1805
            double y = equipment.SPPID.ORIGINAL_Y;
1806
            int mirror = 0;
1807
            double angle = equipment.ANGLE;
1808

    
1809
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1810

    
1811
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1812
            if (connector != null)
1813
            {
1814
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1815
                if (connEquipment != null)
1816
                {
1817
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1818
                        EquipmentModeling(connEquipment);
1819

    
1820
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1821
                    {
1822
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1823
                        if (targetItem != null)
1824
                        {
1825
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1826
                        }
1827
                        else
1828
                        {
1829
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1830
                        }
1831
                    }
1832
                    else
1833
                    {
1834
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1835
                    }
1836
                }
1837
                else
1838
                {
1839
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1840
                }
1841
            }
1842
            else
1843
            {
1844
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1845
            }
1846

    
1847
            if (_LMSymbol != null)
1848
            {
1849
                _LMSymbol.Commit();
1850
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1851
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1852
                ReleaseCOMObjects(_LMSymbol);
1853
            }
1854

    
1855
            if (targetItem != null)
1856
            {
1857
                ReleaseCOMObjects(targetItem);
1858
            }
1859

    
1860
            ReleaseCOMObjects(_LMSymbol);
1861
        }
1862

    
1863
        /// <summary>
1864
        /// 첫 진입점
1865
        /// </summary>
1866
        /// <param name="symbol"></param>
1867
        private void SymbolModelingBySymbol(Symbol symbol)
1868
        {
1869
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1870
            List<object> endObjects = new List<object>();
1871
            endObjects.Add(symbol);
1872

    
1873
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1874
            foreach (var connector in symbol.CONNECTORS)
1875
            {
1876
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1877
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1878
                {
1879
                    endObjects.Add(connItem);
1880
                    if (connItem.GetType() == typeof(Symbol))
1881
                    {
1882
                        Symbol connSymbol = connItem as Symbol;
1883
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1884
                        {
1885
                            SymbolModeling(connSymbol, symbol);
1886
                        }
1887
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1888
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1889
                    }
1890
                    else if (connItem.GetType() == typeof(Line))
1891
                    {
1892
                        Line connLine = connItem as Line;
1893
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1894
                    }
1895
                }
1896
            }
1897
        }
1898

    
1899
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1900
        {
1901
            foreach (var connector in symbol.CONNECTORS)
1902
            {
1903
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1904
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1905
                {
1906
                    if (!endObjects.Contains(connItem))
1907
                    {
1908
                        endObjects.Add(connItem);
1909
                        if (connItem.GetType() == typeof(Symbol))
1910
                        {
1911
                            Symbol connSymbol = connItem as Symbol;
1912
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1913
                            {
1914
                                SymbolModeling(connSymbol, symbol);
1915
                            }
1916
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1917
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1918
                        }
1919
                        else if (connItem.GetType() == typeof(Line))
1920
                        {
1921
                            Line connLine = connItem as Line;
1922
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1923
                        }
1924
                    }
1925
                }
1926
            }
1927
        }
1928

    
1929
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1930
        {
1931
            foreach (var connector in line.CONNECTORS)
1932
            {
1933
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1934
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1935
                {
1936
                    if (!endObjects.Contains(connItem))
1937
                    {
1938
                        endObjects.Add(connItem);
1939
                        if (connItem.GetType() == typeof(Symbol))
1940
                        {
1941
                            Symbol connSymbol = connItem as Symbol;
1942
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1943
                            {
1944
                                List<Symbol> group = new List<Symbol>();
1945
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1946
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1947
                                List<Symbol> endModelingGroup = new List<Symbol>();
1948
                                if (priority != null)
1949
                                {
1950
                                    SymbolGroupModeling(priority, group);
1951

    
1952
                                    // Range 겹치는지 확인해야함
1953
                                    double[] prevRange = null;
1954
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1955
                                    double[] groupRange = null;
1956
                                    GetSPPIDSymbolRange(group, ref groupRange);
1957

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

    
1971
                                        SymbolGroupModeling(priority, group);
1972
                                    }
1973
                                }
1974
                                else
1975
                                {
1976
                                    SymbolModeling(connSymbol, null);
1977
                                    // Range 겹치는지 확인해야함
1978
                                    double[] prevRange = null;
1979
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1980
                                    double[] connRange = null;
1981
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1982

    
1983
                                    double distanceX = 0;
1984
                                    double distanceY = 0;
1985
                                    bool overlapX = false;
1986
                                    bool overlapY = false;
1987
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1988
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1989
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1990
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1991
                                    {
1992
                                        RemoveSymbol(connSymbol);
1993
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1994

    
1995
                                        SymbolModeling(connSymbol, null);
1996
                                    }
1997
                                }
1998
                            }
1999
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2000
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2001
                        }
2002
                        else if (connItem.GetType() == typeof(Line))
2003
                        {
2004
                            Line connLine = connItem as Line;
2005
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2006
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2007
                        }
2008
                    }
2009
                }
2010
            }
2011
        }
2012

    
2013
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2014
        {
2015
            List<Symbol> endModelingGroup = new List<Symbol>();
2016
            SymbolModeling(firstSymbol, null);
2017
            endModelingGroup.Add(firstSymbol);
2018
            while (endModelingGroup.Count != group.Count)
2019
            {
2020
                foreach (var _symbol in group)
2021
                {
2022
                    if (!endModelingGroup.Contains(_symbol))
2023
                    {
2024
                        foreach (var _connector in _symbol.CONNECTORS)
2025
                        {
2026
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2027
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2028
                            {
2029
                                SymbolModeling(_symbol, _connSymbol);
2030
                                endModelingGroup.Add(_symbol);
2031
                                break;
2032
                            }
2033
                        }
2034
                    }
2035
                }
2036
            }
2037
        }
2038

    
2039
        /// <summary>
2040
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2041
        /// </summary>
2042
        /// <param name="childSymbol"></param>
2043
        /// <param name="parentSymbol"></param>
2044
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2045
        {
2046
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2047
            double x1 = 0;
2048
            double x2 = 0;
2049
            double y1 = 0;
2050
            double y2 = 0;
2051
            symbol2d.Range(out x1, out y1, out x2, out y2);
2052

    
2053
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2054
            if (_LMSymbol != null)
2055
            {
2056
                _LMSymbol.Commit();
2057
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2058
                foreach (var item in childSymbol.ChildSymbols)
2059
                    CreateChildSymbol(item, _LMSymbol, parent);
2060
            }
2061

    
2062

    
2063
            ReleaseCOMObjects(_LMSymbol);
2064
        }
2065
        double index = 0;
2066
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2067
        {
2068
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2069
                return;
2070

    
2071
            List<Line> group = new List<Line>();
2072
            GetConnectedLineGroup(line, group);
2073
            LineCoordinateCorrection(group);
2074

    
2075
            foreach (var groupLine in group)
2076
            {
2077
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2078
                {
2079
                    BranchLines.Add(groupLine);
2080
                    continue;
2081
                }
2082

    
2083
                bool diagonal = false;
2084
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2085
                    diagonal = true;
2086
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2087
                LMSymbol _LMSymbolStart = null;
2088
                LMSymbol _LMSymbolEnd = null;
2089
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2090
                foreach (var connector in groupLine.CONNECTORS)
2091
                {
2092
                    double x = 0;
2093
                    double y = 0;
2094
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2095
                    if (connector.ConnectedObject == null)
2096
                    {
2097
                        placeRunInputs.AddPoint(x, y);
2098
                    }
2099
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2100
                    {
2101
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2102
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2103
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2104
                        {
2105
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2106
                            if (_LMSymbolStart != null)
2107
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2108
                            else
2109
                                placeRunInputs.AddPoint(x, y);
2110
                        }
2111
                        else
2112
                        {
2113
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2114
                            if (_LMSymbolEnd != null)
2115
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2116
                            else
2117
                                placeRunInputs.AddPoint(x, y);
2118
                        }
2119
                    }
2120
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2121
                    {
2122
                        Line targetLine = connector.ConnectedObject as Line;
2123
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2124
                        {
2125
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2126
                            if (targetConnector != null)
2127
                            {
2128
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2129
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2130
                            }
2131
                            else
2132
                            {
2133
                                placeRunInputs.AddPoint( x, y);
2134
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2135
                            }
2136
                        }
2137
                        else
2138
                        {
2139
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2140
                            {
2141
                                index += 0.01;
2142
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2143
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2144
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2145
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2146
                                else
2147
                                {
2148
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2149
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2150
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2151
                                    else
2152
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2153
                                }
2154
                            }
2155

    
2156
                            placeRunInputs.AddPoint(x, y);
2157

    
2158
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2159
                            {
2160
                                index += 0.01;
2161
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2162
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2163
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2164
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2165
                                else
2166
                                {
2167
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2168
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2169
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2170
                                    else
2171
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2172
                                }
2173
                            }
2174
                        }
2175
                    }
2176
                }
2177

    
2178
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2179
                if (_lMConnector != null)
2180
                {
2181
                    _lMConnector.Commit();
2182
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2183

    
2184
                    bool bRemodelingStart = false;
2185
                    if (_LMSymbolStart != null)
2186
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2187
                    bool bRemodelingEnd = false;
2188
                    if (_LMSymbolEnd != null)
2189
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2190

    
2191
                    if (bRemodelingStart || bRemodelingEnd)
2192
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2193

    
2194
                    FlowMarkModeling(groupLine);
2195
                    LineNumberModelingOnlyOne(groupLine);
2196

    
2197
                    ReleaseCOMObjects(_lMConnector);
2198
                }
2199
                else if (!isBranchModeling)
2200
                {
2201
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2202
                }
2203

    
2204
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2205
                x.ConnectedObject != null &&
2206
                x.ConnectedObject.GetType() == typeof(Line) &&
2207
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2208
                .Select(x => x.ConnectedObject)
2209
                .ToList();
2210

    
2211
                foreach (var item in removeLines)
2212
                    RemoveLineForModeling(item as Line);
2213

    
2214
                if (_LMAItem != null)
2215
                    ReleaseCOMObjects(_LMAItem);
2216
                if (placeRunInputs != null)
2217
                    ReleaseCOMObjects(placeRunInputs);
2218
                if (_LMSymbolStart != null)
2219
                    ReleaseCOMObjects(_LMSymbolStart);
2220
                if (_LMSymbolEnd != null)
2221
                    ReleaseCOMObjects(_LMSymbolEnd);
2222

    
2223
                if (isBranchModeling && BranchLines.Contains(groupLine))
2224
                    BranchLines.Remove(groupLine);
2225
            }
2226
        }
2227

    
2228
        private void RemoveLineForModeling(Line line)
2229
        {
2230
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2231
            if (modelItem != null)
2232
            {
2233
                foreach (LMRepresentation rep in modelItem.Representations)
2234
                {
2235
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2236
                    {
2237
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2238
                        dynamic OID = rep.get_GraphicOID().ToString();
2239
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2240
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2241
                        int verticesCount = lineStringGeometry.VertexCount;
2242
                        double[] vertices = null;
2243
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2244
                        for (int i = 0; i < verticesCount; i++)
2245
                        {
2246
                            double x = 0;
2247
                            double y = 0;
2248
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2249
                            if (verticesCount == 2 && (x < 0 || y < 0))
2250
                                _placement.PIDRemovePlacement(rep);
2251
                        }
2252
                        ReleaseCOMObjects(_LMConnector);
2253
                    }
2254
                }
2255

    
2256
                ReleaseCOMObjects(modelItem);
2257
            }
2258
        }
2259

    
2260
        private void GetConnectedLineGroup(Line line, List<Line> group)
2261
        {
2262
            if (!group.Contains(line))
2263
                group.Add(line);
2264
            foreach (var connector in line.CONNECTORS)
2265
            {
2266
                if (connector.ConnectedObject != null &&
2267
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2268
                    !group.Contains(connector.ConnectedObject) &&
2269
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2270
                {
2271
                    Line connLine = connector.ConnectedObject as Line;
2272
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2273
                    {
2274
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2275
                            group.Insert(0, connLine);
2276
                        else
2277
                            group.Add(connLine);
2278
                        GetConnectedLineGroup(connLine, group);
2279
                    }
2280
                }
2281
            }
2282
        }
2283

    
2284
        private void LineCoordinateCorrection(List<Line> group)
2285
        {
2286
            // 순서대로 전 Item 기준 정렬
2287
            LineCoordinateCorrectionByStart(group);
2288

    
2289
            // 역으로 심볼이 있을 경우 좌표 보정
2290
            LineCoordinateCorrectionForLastLine(group);
2291
        }
2292

    
2293
        private void LineCoordinateCorrectionByStart(List<Line> group)
2294
        {
2295
            for (int i = 0; i < group.Count; i++)
2296
            {
2297
                Line line = group[i];
2298
                if (i == 0)
2299
                {
2300
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2301
                    if (symbolConnector != null)
2302
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2303
                }
2304
                else if (i != 0)
2305
                {
2306
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2307
                }
2308
            }
2309
        }
2310

    
2311
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2312
        {
2313
            Line checkLine = group[group.Count - 1];
2314
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2315
            if (lastSymbolConnector != null)
2316
            {
2317
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2318
                for (int i = group.Count - 2; i >= 0; i--)
2319
                {
2320
                    Line line = group[i + 1];
2321
                    Line prevLine = group[i];
2322

    
2323
                    // 같으면 보정
2324
                    if (line.SlopeType == prevLine.SlopeType)
2325
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2326
                    else
2327
                    {
2328
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2329
                        {
2330
                            double prevX = 0;
2331
                            double prevY = 0;
2332
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2333
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2334

    
2335
                            double x = 0;
2336
                            double y = 0;
2337
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2338
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2339
                        }
2340
                        else if (line.SlopeType == SlopeType.VERTICAL)
2341
                        {
2342
                            double prevX = 0;
2343
                            double prevY = 0;
2344
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2345
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2346

    
2347
                            double x = 0;
2348
                            double y = 0;
2349
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2350
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2351
                        }
2352
                        break;
2353
                    }
2354
                }
2355
            }
2356
        }
2357

    
2358
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2359
        {
2360
            double x = 0;
2361
            double y = 0;
2362
            if (connItem.GetType() == typeof(Symbol))
2363
            {
2364
                Symbol targetSymbol = connItem as Symbol;
2365
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2366
                if (targetConnector != null)
2367
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2368
                else
2369
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2370
            }
2371
            else if (connItem.GetType() == typeof(Line))
2372
            {
2373
                Line targetLine = connItem as Line;
2374
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2375
            }
2376

    
2377
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2378
        }
2379

    
2380
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2381
        {
2382
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2383
            int index = line.CONNECTORS.IndexOf(connector);
2384
            if (index == 0)
2385
            {
2386
                line.SPPID.START_X = x;
2387
                line.SPPID.START_Y = y;
2388
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2389
                    line.SPPID.END_Y = y;
2390
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2391
                    line.SPPID.END_X = x;
2392
            }
2393
            else
2394
            {
2395
                line.SPPID.END_X = x;
2396
                line.SPPID.END_Y = y;
2397
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2398
                    line.SPPID.START_Y = y;
2399
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2400
                    line.SPPID.START_X = x;
2401
            }
2402
        }
2403

    
2404
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2405
        {
2406
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2407
            int index = line.CONNECTORS.IndexOf(connector);
2408
            if (index == 0)
2409
            {
2410
                line.SPPID.START_X = x;
2411
                if (line.SlopeType == SlopeType.VERTICAL)
2412
                    line.SPPID.END_X = x;
2413
            }
2414
            else
2415
            {
2416
                line.SPPID.END_X = x;
2417
                if (line.SlopeType == SlopeType.VERTICAL)
2418
                    line.SPPID.START_X = x;
2419
            }
2420
        }
2421

    
2422
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2423
        {
2424
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2425
            int index = line.CONNECTORS.IndexOf(connector);
2426
            if (index == 0)
2427
            {
2428
                line.SPPID.START_Y = y;
2429
                if (line.SlopeType == SlopeType.HORIZONTAL)
2430
                    line.SPPID.END_Y = y;
2431
            }
2432
            else
2433
            {
2434
                line.SPPID.END_Y = y;
2435
                if (line.SlopeType == SlopeType.HORIZONTAL)
2436
                    line.SPPID.START_Y = y;
2437
            }
2438
        }
2439

    
2440
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2441
        {
2442
            if (symbol != null)
2443
            {
2444
                string repID = symbol.AsLMRepresentation().Id;
2445
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2446
                string lineUID = line.UID;
2447

    
2448
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2449
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2450
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2451

    
2452
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2453
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2454
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2455

    
2456
                if (startSpecBreak != null || startEndBreak != null)
2457
                    result = true;
2458
            }
2459
        }
2460

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

    
2487
            List<double[]> vertices = new List<double[]>();
2488
            for (int i = 1; i <= verticesCount; i++)
2489
            {
2490
                double x = 0;
2491
                double y = 0;
2492
                lineStringGeometry.GetVertex(i, ref x, ref y);
2493
                vertices.Add(new double[] { x, y });
2494
            }
2495

    
2496
            for (int i = 0; i < vertices.Count; i++)
2497
            {
2498
                double[] points = vertices[i];
2499
                // 시작 심볼이 있고 첫번째 좌표일 때
2500
                if (startSymbol != null && i == 0)
2501
                {
2502
                    if (bStart)
2503
                    {
2504
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2505
                        if (slopeType == SlopeType.HORIZONTAL)
2506
                            placeRunInputs.AddPoint(points[0], -0.1);
2507
                        else if (slopeType == SlopeType.VERTICAL)
2508
                            placeRunInputs.AddPoint(-0.1, points[1]);
2509
                        else
2510
                            placeRunInputs.AddPoint(points[0], -0.1);
2511

    
2512
                        placeRunInputs.AddPoint(points[0], points[1]);
2513
                    }
2514
                    else
2515
                    {
2516
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2517
                    }
2518
                }
2519
                // 마지막 심볼이 있고 마지막 좌표일 때
2520
                else if (endSymbol != null && i == vertices.Count - 1)
2521
                {
2522
                    if (bEnd)
2523
                    {
2524
                        placeRunInputs.AddPoint(points[0], points[1]);
2525

    
2526
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2527
                        if (slopeType == SlopeType.HORIZONTAL)
2528
                            placeRunInputs.AddPoint(points[0], -0.1);
2529
                        else if (slopeType == SlopeType.VERTICAL)
2530
                            placeRunInputs.AddPoint(-0.1, points[1]);
2531
                        else
2532
                            placeRunInputs.AddPoint(points[0], -0.1);
2533
                    }
2534
                    else
2535
                    {
2536
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2537
                    }
2538
                }
2539
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2540
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2541
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2542
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2543
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2544
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2545
                else
2546
                    placeRunInputs.AddPoint(points[0], points[1]);
2547
            }
2548

    
2549
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2550
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2551

    
2552
            ReleaseCOMObjects(placeRunInputs);
2553
            ReleaseCOMObjects(_LMAItem);
2554
            ReleaseCOMObjects(modelItem);
2555

    
2556
            if (newConnector != null)
2557
            {
2558
                newConnector.Commit();
2559
                if (startSymbol != null && bStart)
2560
                {
2561
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2562
                    placeRunInputs = new PlaceRunInputs();
2563
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2564
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2565
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2566
                    if (_LMConnector != null)
2567
                    {
2568
                        _LMConnector.Commit();
2569
                        RemoveConnectorForReModelingLine(newConnector);
2570
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2571
                        ReleaseCOMObjects(_LMConnector);
2572
                    }
2573
                    ReleaseCOMObjects(placeRunInputs);
2574
                    ReleaseCOMObjects(_LMAItem);
2575
                }
2576

    
2577
                if (endSymbol != null && bEnd)
2578
                {
2579
                    if (startSymbol != null)
2580
                    {
2581
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2582
                        newConnector = dicVertices.First().Key;
2583
                    }
2584

    
2585
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2586
                    placeRunInputs = new PlaceRunInputs();
2587
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2588
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2589
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2590
                    if (_LMConnector != null)
2591
                    {
2592
                        _LMConnector.Commit();
2593
                        RemoveConnectorForReModelingLine(newConnector);
2594
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2595
                        ReleaseCOMObjects(_LMConnector);
2596
                    }
2597
                    ReleaseCOMObjects(placeRunInputs);
2598
                    ReleaseCOMObjects(_LMAItem);
2599
                }
2600

    
2601
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2602
                ReleaseCOMObjects(newConnector);
2603
            }
2604

    
2605
            ReleaseCOMObjects(modelItem);
2606
        }
2607

    
2608
        /// <summary>
2609
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2610
        /// </summary>
2611
        /// <param name="connector"></param>
2612
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2613
        {
2614
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2615
            foreach (var item in dicVertices)
2616
            {
2617
                if (item.Value.Count == 2)
2618
                {
2619
                    bool result = false;
2620
                    foreach (var point in item.Value)
2621
                    {
2622
                        if (point[0] < 0 || point[1] < 0)
2623
                        {
2624
                            result = true;
2625
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2626
                            break;
2627
                        }
2628
                    }
2629

    
2630
                    if (result)
2631
                        break;
2632
                }
2633
            }
2634
            foreach (var item in dicVertices)
2635
                ReleaseCOMObjects(item.Key);
2636
        }
2637

    
2638
        /// <summary>
2639
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2640
        /// </summary>
2641
        /// <param name="symbol"></param>
2642
        /// <param name="line"></param>
2643
        /// <returns></returns>
2644
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2645
        {
2646
            LMSymbol _LMSymbol = null;
2647
            foreach (var connector in symbol.CONNECTORS)
2648
            {
2649
                if (connector.CONNECTEDITEM == line.UID)
2650
                {
2651
                    if (connector.Index == 0)
2652
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2653
                    else
2654
                    {
2655
                        ChildSymbol child = null;
2656
                        foreach (var childSymbol in symbol.ChildSymbols)
2657
                        {
2658
                            if (childSymbol.Connectors.Contains(connector))
2659
                                child = childSymbol;
2660
                            else
2661
                                child = GetChildSymbolByConnector(childSymbol, connector);
2662

    
2663
                            if (child != null)
2664
                                break;
2665
                        }
2666

    
2667
                        if (child != null)
2668
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2669
                    }
2670

    
2671
                    break;
2672
                }
2673
            }
2674

    
2675
            return _LMSymbol;
2676
        }
2677

    
2678
        /// <summary>
2679
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2680
        /// </summary>
2681
        /// <param name="item"></param>
2682
        /// <param name="connector"></param>
2683
        /// <returns></returns>
2684
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2685
        {
2686
            foreach (var childSymbol in item.ChildSymbols)
2687
            {
2688
                if (childSymbol.Connectors.Contains(connector))
2689
                    return childSymbol;
2690
                else
2691
                    return GetChildSymbolByConnector(childSymbol, connector);
2692
            }
2693

    
2694
            return null;
2695
        }
2696

    
2697
        /// <summary>
2698
        /// EndBreak 모델링 메서드
2699
        /// </summary>
2700
        /// <param name="endBreak"></param>
2701
        private void EndBreakModeling(EndBreak endBreak)
2702
        {
2703
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2704
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2705

    
2706
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2707
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
2708
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2709

    
2710
            if (targetLMConnector != null)
2711
            {
2712
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2713
                Array array = null;
2714
                if (point != null)
2715
                    array = new double[] { 0, point[0], point[1] };
2716
                else
2717
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2718
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2719
                if (_LmLabelPersist != null)
2720
                {
2721
                    _LmLabelPersist.Commit();
2722
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2723
                    if (_LmLabelPersist.ModelItemObject != null)
2724
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2725
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2726
                    ReleaseCOMObjects(_LmLabelPersist);
2727
                }
2728
                ReleaseCOMObjects(targetLMConnector);
2729
            }
2730
            else
2731
            {
2732
                Log.Write("End Break UID : " + endBreak.UID);
2733
                Log.Write("Can't find targetLMConnector");
2734
            }
2735
        }
2736

    
2737
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
2738
        {
2739
            string symbolPath = string.Empty;
2740
            #region get symbol path
2741
            if (string.IsNullOrEmpty(changeSymbolPath))
2742
            {
2743
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2744
                symbolPath = GetSPPIDFileName(modelItem);
2745
                ReleaseCOMObjects(modelItem);
2746
            }
2747
            else
2748
                symbolPath = changeSymbolPath;
2749
            
2750
            #endregion
2751

    
2752
            LMConnector newConnector = null;
2753
            dynamic OID = connector.get_GraphicOID().ToString();
2754
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2755
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2756
            int verticesCount = lineStringGeometry.VertexCount;
2757
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2758
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2759

    
2760
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2761
            {
2762
                double[] vertices = null;
2763
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2764
                double x = 0;
2765
                double y = 0;
2766
                lineStringGeometry.GetVertex(1, ref x, ref y);
2767

    
2768
                string flowDirection = string.Empty;
2769
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2770
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2771
                    flowDirection = flowAttribute.get_Value().ToString();
2772

    
2773
                if (flowDirection == "End 1 is downstream (Outlet)")
2774
                {
2775
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2776
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2777
                    flowDirection = "End 1 is upstream (Inlet)";
2778
                }
2779
                else
2780
                {
2781
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2782
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2783
                }
2784
                string oldModelItemId = connector.ModelItemID;
2785
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2786
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2787
                newConnector.Commit();
2788
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2789
                if (!string.IsNullOrEmpty(flowDirection))
2790
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2791
                ReleaseCOMObjects(connector);
2792

    
2793
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
2794
                {
2795
                    foreach (var repId in line.SPPID.Representations)
2796
                    {
2797
                        LMConnector _connector = dataSource.GetConnector(repId);
2798
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
2799
                        {
2800
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
2801
                            {
2802
                                line.SPPID.ModelItemId = _connector.ModelItemID;
2803
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
2804
                            }
2805
                        }
2806
                        ReleaseCOMObjects(_connector);
2807
                        _connector = null;
2808
                    }
2809
                }
2810
            }
2811

    
2812
            return newConnector;
2813
        }
2814

    
2815
        /// <summary>
2816
        /// SpecBreak Modeling 메서드
2817
        /// </summary>
2818
        /// <param name="specBreak"></param>
2819
        private void SpecBreakModeling(SpecBreak specBreak)
2820
        {
2821
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2822
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2823

    
2824
            if (upStreamObj != null &&
2825
                downStreamObj != null)
2826
            {
2827
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2828
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && targetLMConnector != null)
2829
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2830

    
2831
                if (targetLMConnector != null)
2832
                {
2833
                    foreach (var attribute in specBreak.ATTRIBUTES)
2834
                    {
2835
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2836
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2837
                        {
2838
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2839
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2840
                            Array array = null;
2841
                            if (point != null)
2842
                                array = new double[] { 0, point[0], point[1] };
2843
                            else
2844
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2845
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2846

    
2847
                            if (_LmLabelPersist != null)
2848
                            {
2849
                                _LmLabelPersist.Commit();
2850
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2851
                                if (_LmLabelPersist.ModelItemObject != null)
2852
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2853
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2854
                                ReleaseCOMObjects(_LmLabelPersist);
2855
                            }
2856
                        }
2857
                    }
2858
                    ReleaseCOMObjects(targetLMConnector);
2859
                }
2860
                else
2861
                {
2862
                    Log.Write("Spec Break UID : " + specBreak.UID);
2863
                    Log.Write("Can't find targetLMConnector");
2864
                }
2865
            }
2866
        }
2867

    
2868
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2869
        {
2870
            LMConnector targetConnector = null;
2871
            Symbol targetSymbol = targetObj as Symbol;
2872
            Symbol connectedSymbol = connectedObj as Symbol;
2873
            Line targetLine = targetObj as Line;
2874
            Line connectedLine = connectedObj as Line;
2875
            if (targetSymbol != null && connectedSymbol != null)
2876
            {
2877
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2878
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2879

    
2880
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2881
                {
2882
                    if (connector.get_ItemStatus() != "Active")
2883
                        continue;
2884

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

    
2897
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2898
                {
2899
                    if (connector.get_ItemStatus() != "Active")
2900
                        continue;
2901

    
2902
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2903
                    {
2904
                        targetConnector = connector;
2905
                        break;
2906
                    }
2907
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2908
                    {
2909
                        targetConnector = connector;
2910
                        break;
2911
                    }
2912
                }
2913

    
2914
                ReleaseCOMObjects(targetLMSymbol);
2915
                ReleaseCOMObjects(connectedLMSymbol);
2916
            }
2917
            else if (targetLine != null && connectedLine != null)
2918
            {
2919
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2920
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2921

    
2922
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2923
                {
2924
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2925
                    {
2926
                        if (targetConnector != null)
2927
                            break;
2928

    
2929
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2930
                        {
2931
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2932

    
2933
                            if (IsConnected(_LMConnector, connectedModelItem))
2934
                                targetConnector = _LMConnector;
2935
                            else
2936
                                ReleaseCOMObjects(_LMConnector);
2937
                        }
2938
                    }
2939

    
2940
                    ReleaseCOMObjects(targetModelItem);
2941
                }
2942
            }
2943
            else
2944
            {
2945
                LMSymbol connectedLMSymbol = null;
2946
                if (connectedSymbol != null)
2947
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2948
                else if (targetSymbol != null)
2949
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2950
                else
2951
                {
2952

    
2953
                }
2954
                LMModelItem targetModelItem = null;
2955
                if (targetLine != null)
2956
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2957
                else if (connectedLine != null)
2958
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2959
                else
2960
                {
2961

    
2962
                }
2963
                if (connectedLMSymbol != null && targetModelItem != null)
2964
                {
2965
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2966
                    {
2967
                        if (connector.get_ItemStatus() != "Active")
2968
                            continue;
2969

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

    
2977
                    if (targetConnector == null)
2978
                    {
2979
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2980
                        {
2981
                            if (connector.get_ItemStatus() != "Active")
2982
                                continue;
2983

    
2984
                            if (IsConnected(connector, targetModelItem))
2985
                            {
2986
                                targetConnector = connector;
2987
                                break;
2988
                            }
2989
                        }
2990
                    }
2991
                }
2992

    
2993
            }
2994

    
2995
            return targetConnector;
2996
        }
2997

    
2998
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2999
        {
3000
            double[] result = null;
3001
            Line targetLine = targetObj as Line;
3002
            Symbol targetSymbol = targetObj as Symbol;
3003
            Line connLine = connObj as Line;
3004
            Symbol connSymbol = connObj as Symbol;
3005

    
3006
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
3007
            double lineMove = GridSetting.GetInstance().Length * 3;
3008
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3009
            {
3010
                result = GetConnectorVertices(targetConnector)[0];
3011
                if (targetSymbol != null && connSymbol != null)
3012
                {
3013
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3014
                    if (slopeType == SlopeType.HORIZONTAL)
3015
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3016
                    else if (slopeType == SlopeType.VERTICAL)
3017
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3018
                }
3019
                else if (targetLine != null)
3020
                {
3021
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3022
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3023
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3024
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3025
                }
3026
                else if (connLine != null)
3027
                {
3028
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3029
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3030
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3031
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3032
                }
3033
            }
3034
            else
3035
            {
3036
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3037
                {
3038
                    Line line = connObj as Line;
3039
                    LMConnector connectedConnector = null;
3040
                    int connIndex = 0;
3041
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3042
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3043

    
3044
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3045

    
3046
                    ReleaseCOMObjects(modelItem);
3047
                    ReleaseCOMObjects(connectedConnector);
3048

    
3049
                    if (vertices.Count > 0)
3050
                    {
3051
                        if (connIndex == 1)
3052
                            result = vertices[0];
3053
                        else if (connIndex == 2)
3054
                            result = vertices[vertices.Count - 1];
3055

    
3056
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3057
                        {
3058
                            result = new double[] { result[0], result[1] - lineMove };
3059
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3060
                            {
3061
                                result = new double[] { result[0] - lineMove, result[1] };
3062
                            }
3063
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3064
                            {
3065
                                result = new double[] { result[0] + lineMove, result[1] };
3066
                            }
3067
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3068
                            {
3069
                                result = new double[] { result[0] + lineMove, result[1] };
3070
                            }
3071
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3072
                            {
3073
                                result = new double[] { result[0] - lineMove, result[1] };
3074
                            }
3075
                        }
3076
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3077
                        {
3078
                            result = new double[] { result[0] - lineMove, result[1] };
3079
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3080
                            {
3081
                                result = new double[] { result[0], result[1] - lineMove };
3082
                            }
3083
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3084
                            {
3085
                                result = new double[] { result[0], result[1] + lineMove };
3086
                            }
3087
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3088
                            {
3089
                                result = new double[] { result[0], result[1] + lineMove };
3090
                            }
3091
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3092
                            {
3093
                                result = new double[] { result[0], result[1] - lineMove };
3094
                            }
3095
                        }
3096
                            
3097
                    }
3098
                }
3099
                else
3100
                {
3101
                    Log.Write("error in GetSegemtPoint");
3102
                }
3103
            }
3104

    
3105
            return result;
3106
        }
3107

    
3108
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3109
        {
3110
            bool result = false;
3111

    
3112
            foreach (LMRepresentation rep in modelItem.Representations)
3113
            {
3114
                if (result)
3115
                    break;
3116

    
3117
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3118
                {
3119
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3120

    
3121
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3122
                        connector.ConnectItem1SymbolObject != null &&
3123
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3124
                    {
3125
                        result = true;
3126
                        ReleaseCOMObjects(_LMConnector);
3127
                        break;
3128
                    }
3129
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3130
                        connector.ConnectItem2SymbolObject != null &&
3131
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3132
                    {
3133
                        result = true;
3134
                        ReleaseCOMObjects(_LMConnector);
3135
                        break;
3136
                    }
3137
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3138
                        connector.ConnectItem1SymbolObject != null &&
3139
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3140
                    {
3141
                        result = true;
3142
                        ReleaseCOMObjects(_LMConnector);
3143
                        break;
3144
                    }
3145
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3146
                        connector.ConnectItem2SymbolObject != null &&
3147
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3148
                    {
3149
                        result = true;
3150
                        ReleaseCOMObjects(_LMConnector);
3151
                        break;
3152
                    }
3153

    
3154
                    ReleaseCOMObjects(_LMConnector);
3155
                }
3156
            }
3157

    
3158

    
3159
            return result;
3160
        }
3161

    
3162
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3163
        {
3164
            foreach (LMRepresentation rep in modelItem.Representations)
3165
            {
3166
                if (connectedConnector != null)
3167
                    break;
3168

    
3169
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3170
                {
3171
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3172

    
3173
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3174
                        connector.ConnectItem1SymbolObject != null &&
3175
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3176
                    {
3177
                        connectedConnector = _LMConnector;
3178
                        connectorIndex = 1;
3179
                        break;
3180
                    }
3181
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3182
                        connector.ConnectItem2SymbolObject != null &&
3183
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3184
                    {
3185
                        connectedConnector = _LMConnector;
3186
                        connectorIndex = 2;
3187
                        break;
3188
                    }
3189
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3190
                        connector.ConnectItem1SymbolObject != null &&
3191
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3192
                    {
3193
                        connectedConnector = _LMConnector;
3194
                        connectorIndex = 1;
3195
                        break;
3196
                    }
3197
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3198
                        connector.ConnectItem2SymbolObject != null &&
3199
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3200
                    {
3201
                        connectedConnector = _LMConnector;
3202
                        connectorIndex = 2;
3203
                        break;
3204
                    }
3205

    
3206
                    if (connectedConnector == null)
3207
                        ReleaseCOMObjects(_LMConnector);
3208
                }
3209
            }
3210
        }
3211

    
3212
        /// <summary>
3213
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3214
        /// </summary>
3215
        /// <param name="modelItemID1"></param>
3216
        /// <param name="modelItemID2"></param>
3217
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
3218
        {
3219
            try
3220
            {
3221
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3222
                _LMAItem item1 = modelItem1.AsLMAItem();
3223
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3224
                _LMAItem item2 = modelItem2.AsLMAItem();
3225

    
3226
                // item2가 item1으로 조인
3227
                _placement.PIDJoinRuns(ref item1, ref item2);
3228
                item1.Commit();
3229
                item2.Commit();
3230

    
3231
                string beforeID = string.Empty;
3232
                string afterID = string.Empty;
3233

    
3234
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3235
                {
3236
                    beforeID = modelItem2.Id;
3237
                    afterID = modelItem1.Id;
3238
                    survivorId = afterID;
3239
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
3240
                    if (attribute != null)
3241
                        attribute.set_Value("End 1 is upstream (Inlet)");
3242
                }
3243
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3244
                {
3245
                    beforeID = modelItem1.Id;
3246
                    afterID = modelItem2.Id;
3247
                    survivorId = afterID;
3248
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
3249
                    if (attribute != null)
3250
                        attribute.set_Value("End 1 is upstream (Inlet)");
3251
                }
3252
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3253
                {
3254
                    int model1Cnt = GetConnectorCount(modelId1);
3255
                    int model2Cnt = GetConnectorCount(modelId2);
3256
                    if (model1Cnt == 0)
3257
                    {
3258
                        beforeID = modelItem1.Id;
3259
                        afterID = modelItem2.Id;
3260
                        survivorId = afterID;
3261
                        LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
3262
                        if (attribute != null)
3263
                            attribute.set_Value("End 1 is upstream (Inlet)");
3264
                    }
3265
                    else if (model2Cnt == 0)
3266
                    {
3267
                        beforeID = modelItem2.Id;
3268
                        afterID = modelItem1.Id;
3269
                        survivorId = afterID;
3270
                        LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
3271
                        if (attribute != null)
3272
                            attribute.set_Value("End 1 is upstream (Inlet)");
3273
                    }
3274
                    else
3275
                        survivorId = null;
3276
                }
3277
                else
3278
                {
3279
                    Log.Write("잘못된 경우");
3280
                    survivorId = null;
3281
                }
3282

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

    
3290
                ReleaseCOMObjects(modelItem1);
3291
                ReleaseCOMObjects(item1);
3292
                ReleaseCOMObjects(modelItem2);
3293
                ReleaseCOMObjects(item2);
3294
            }
3295
            catch (Exception ex)
3296
            {
3297
                Log.Write("Join Error");
3298
                Log.Write(ex.Message);
3299
            }
3300
        }
3301

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

    
3311
                LMModelItem modelItem = connector.ModelItemObject;
3312
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3313
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3314
                    temp.Add(modelItem.Id);
3315

    
3316
                if (temp.Contains(modelItem.Id) &&
3317
                    connOtherSymbol != null &&
3318
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3319
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3320
                    temp.Remove(modelItem.Id);
3321

    
3322

    
3323
                if (temp.Contains(modelItem.Id))
3324
                    connectors.Add(connector);
3325
                ReleaseCOMObjects(connOtherSymbol);
3326
                connOtherSymbol = null;
3327
                ReleaseCOMObjects(modelItem);
3328
                modelItem = null;
3329
            }
3330

    
3331
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3332
            {
3333
                if (connector.get_ItemStatus() != "Active")
3334
                    continue;
3335

    
3336
                LMModelItem modelItem = connector.ModelItemObject;
3337
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3338
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3339
                    temp.Add(modelItem.Id);
3340

    
3341
                if (temp.Contains(modelItem.Id) &&
3342
                    connOtherSymbol != null &&
3343
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3344
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3345
                    temp.Remove(modelItem.Id);
3346

    
3347
                if (temp.Contains(modelItem.Id))
3348
                    connectors.Add(connector);
3349
                ReleaseCOMObjects(connOtherSymbol);
3350
                connOtherSymbol = null;
3351
                ReleaseCOMObjects(modelItem);
3352
                modelItem = null;
3353
            }
3354

    
3355

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

    
3377
            foreach (var connector in connectors)
3378
                ReleaseCOMObjects(connector);
3379
            
3380
            return result;
3381

    
3382

    
3383
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3384
            {
3385
                LMSymbol findResult = null;
3386
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3387
                    findResult = connector.ConnectItem1SymbolObject;
3388
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3389
                    findResult = connector.ConnectItem2SymbolObject;
3390

    
3391
                return findResult;
3392
            }
3393
        }
3394

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

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

    
3435
                ReleaseCOMObjects(modelItem);
3436
            }
3437

    
3438
            return connectorVertices;
3439
        }
3440

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

    
3463
        /// <summary>
3464
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3465
        /// </summary>
3466
        /// <param name="connectorVertices"></param>
3467
        /// <param name="connX"></param>
3468
        /// <param name="connY"></param>
3469
        /// <returns></returns>
3470
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3471
        {
3472
            double length = double.MaxValue;
3473
            LMConnector targetConnector = null;
3474
            foreach (var item in connectorVertices)
3475
            {
3476
                List<double[]> points = item.Value;
3477
                for (int i = 0; i < points.Count - 1; i++)
3478
                {
3479
                    double[] point1 = points[i];
3480
                    double[] point2 = points[i + 1];
3481
                    double x1 = Math.Min(point1[0], point2[0]);
3482
                    double y1 = Math.Min(point1[1], point2[1]);
3483
                    double x2 = Math.Max(point1[0], point2[0]);
3484
                    double y2 = Math.Max(point1[1], point2[1]);
3485

    
3486
                    if ((x1 <= connX && x2 >= connX) ||
3487
                        (y1 <= connY && y2 >= connY))
3488
                    {
3489
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3490
                        if (length >= distance)
3491
                        {
3492
                            targetConnector = item.Key;
3493
                            length = distance;
3494
                        }
3495

    
3496
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3497
                        if (length >= distance)
3498
                        {
3499
                            targetConnector = item.Key;
3500
                            length = distance;
3501
                        }
3502
                    }
3503
                }
3504
            }
3505

    
3506
            // 못찾았을때.
3507
            length = double.MaxValue;
3508
            if (targetConnector == null)
3509
            {
3510
                foreach (var item in connectorVertices)
3511
                {
3512
                    List<double[]> points = item.Value;
3513

    
3514
                    foreach (double[] point in points)
3515
                    {
3516
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3517
                        if (length >= distance)
3518
                        {
3519
                            targetConnector = item.Key;
3520
                            length = distance;
3521
                        }
3522
                    }
3523
                }
3524
            }
3525

    
3526
            return targetConnector;
3527
        }
3528

    
3529
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3530
        {
3531
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3532
            if (vertices.Count == 0)
3533
                return null;
3534

    
3535
            double length = double.MaxValue;
3536
            LMConnector targetConnector = null;
3537
            double[] resultPoint = null;
3538
            List<double[]> targetVertices = null;
3539

    
3540
            // Vertices 포인트에 제일 가까운곳
3541
            foreach (var item in vertices)
3542
            {
3543
                List<double[]> points = item.Value;
3544
                for (int i = 0; i < points.Count; i++)
3545
                {
3546
                    double[] point = points[i];
3547
                    double tempX = point[0];
3548
                    double tempY = point[1];
3549

    
3550
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3551
                    if (length >= distance)
3552
                    {
3553
                        targetConnector = item.Key;
3554
                        length = distance;
3555
                        resultPoint = point;
3556
                        targetVertices = item.Value;
3557
                    }
3558
                }
3559
            }
3560

    
3561
            // Vertices Cross에 제일 가까운곳
3562
            foreach (var item in vertices)
3563
            {
3564
                List<double[]> points = item.Value;
3565
                for (int i = 0; i < points.Count - 1; i++)
3566
                {
3567
                    double[] point1 = points[i];
3568
                    double[] point2 = points[i + 1];
3569

    
3570
                    double maxLineX = Math.Max(point1[0], point2[0]);
3571
                    double minLineX = Math.Min(point1[0], point2[0]);
3572
                    double maxLineY = Math.Max(point1[1], point2[1]);
3573
                    double minLineY = Math.Min(point1[1], point2[1]);
3574

    
3575
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3576

    
3577
                    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]);
3578
                    if (crossingPoint != null)
3579
                    {
3580
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3581
                        if (length >= distance)
3582
                        {
3583
                            if (slope == SlopeType.Slope &&
3584
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3585
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3586
                            {
3587
                                targetConnector = item.Key;
3588
                                length = distance;
3589
                                resultPoint = crossingPoint;
3590
                                targetVertices = item.Value;
3591
                            }
3592
                            else if (slope == SlopeType.HORIZONTAL &&
3593
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3594
                            {
3595
                                targetConnector = item.Key;
3596
                                length = distance;
3597
                                resultPoint = crossingPoint;
3598
                                targetVertices = item.Value;
3599
                            }
3600
                            else if (slope == SlopeType.VERTICAL &&
3601
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3602
                            {
3603
                                targetConnector = item.Key;
3604
                                length = distance;
3605
                                resultPoint = crossingPoint;
3606
                                targetVertices = item.Value;
3607
                            }
3608
                        }
3609
                    }
3610
                }
3611
            }
3612

    
3613
            foreach (var item in vertices)
3614
                if (item.Key != null && item.Key != targetConnector)
3615
                    ReleaseCOMObjects(item.Key);
3616

    
3617
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3618
            {
3619
                double tempResultX = resultPoint[0];
3620
                double tempResultY = resultPoint[1];
3621
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3622

    
3623
                GridSetting gridSetting = GridSetting.GetInstance();
3624

    
3625
                for (int i = 0; i < targetVertices.Count; i++)
3626
                {
3627
                    double[] point = targetVertices[i];
3628
                    double tempX = targetVertices[i][0];
3629
                    double tempY = targetVertices[i][1];
3630
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3631
                    if (tempX == tempResultX && tempY == tempResultY)
3632
                    {
3633
                        if (i == 0)
3634
                        {
3635
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3636
                            bool containZeroLength = false;
3637
                            if (connSymbol != null)
3638
                            {
3639
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3640
                                {
3641
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3642
                                        containZeroLength = true;
3643
                                }
3644
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3645
                                {
3646
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3647
                                        containZeroLength = true;
3648
                                }
3649
                            }
3650

    
3651
                            if (connSymbol == null ||
3652
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3653
                                containZeroLength)
3654
                            {
3655
                                bool bCalcX = false;
3656
                                bool bCalcY = false;
3657
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3658
                                    bCalcX = true;
3659
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3660
                                    bCalcY = true;
3661
                                else
3662
                                {
3663
                                    bCalcX = true;
3664
                                    bCalcY = true;
3665
                                }
3666

    
3667
                                if (bCalcX)
3668
                                {
3669
                                    double nextX = targetVertices[i + 1][0];
3670
                                    double newX = 0;
3671
                                    if (nextX > tempX)
3672
                                    {
3673
                                        newX = tempX + gridSetting.Length;
3674
                                        if (newX > nextX)
3675
                                            newX = (point[0] + nextX) / 2;
3676
                                    }
3677
                                    else
3678
                                    {
3679
                                        newX = tempX - gridSetting.Length;
3680
                                        if (newX < nextX)
3681
                                            newX = (point[0] + nextX) / 2;
3682
                                    }
3683
                                    resultPoint = new double[] { newX, resultPoint[1] };
3684
                                }
3685

    
3686
                                if (bCalcY)
3687
                                {
3688
                                    double nextY = targetVertices[i + 1][1];
3689
                                    double newY = 0;
3690
                                    if (nextY > tempY)
3691
                                    {
3692
                                        newY = tempY + gridSetting.Length;
3693
                                        if (newY > nextY)
3694
                                            newY = (point[1] + nextY) / 2;
3695
                                    }
3696
                                    else
3697
                                    {
3698
                                        newY = tempY - gridSetting.Length;
3699
                                        if (newY < nextY)
3700
                                            newY = (point[1] + nextY) / 2;
3701
                                    }
3702
                                    resultPoint = new double[] { resultPoint[0], newY };
3703
                                }
3704
                            }
3705
                        }
3706
                        else if (i == targetVertices.Count - 1)
3707
                        {
3708
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3709
                            bool containZeroLength = false;
3710
                            if (connSymbol != null)
3711
                            {
3712
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3713
                                {
3714
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3715
                                        containZeroLength = true;
3716
                                }
3717
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3718
                                {
3719
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3720
                                        containZeroLength = true;
3721
                                }
3722
                            }
3723

    
3724
                            if (connSymbol == null ||
3725
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3726
                                containZeroLength)
3727
                            {
3728
                                bool bCalcX = false;
3729
                                bool bCalcY = false;
3730
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3731
                                    bCalcX = true;
3732
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3733
                                    bCalcY = true;
3734
                                else
3735
                                {
3736
                                    bCalcX = true;
3737
                                    bCalcY = true;
3738
                                }
3739

    
3740
                                if (bCalcX)
3741
                                {
3742
                                    double nextX = targetVertices[i - 1][0];
3743
                                    double newX = 0;
3744
                                    if (nextX > tempX)
3745
                                    {
3746
                                        newX = tempX + gridSetting.Length;
3747
                                        if (newX > nextX)
3748
                                            newX = (point[0] + nextX) / 2;
3749
                                    }
3750
                                    else
3751
                                    {
3752
                                        newX = tempX - gridSetting.Length;
3753
                                        if (newX < nextX)
3754
                                            newX = (point[0] + nextX) / 2;
3755
                                    }
3756
                                    resultPoint = new double[] { newX, resultPoint[1] };
3757
                                }
3758

    
3759
                                if (bCalcY)
3760
                                {
3761
                                    double nextY = targetVertices[i - 1][1];
3762
                                    double newY = 0;
3763
                                    if (nextY > tempY)
3764
                                    {
3765
                                        newY = tempY + gridSetting.Length;
3766
                                        if (newY > nextY)
3767
                                            newY = (point[1] + nextY) / 2;
3768
                                    }
3769
                                    else
3770
                                    {
3771
                                        newY = tempY - gridSetting.Length;
3772
                                        if (newY < nextY)
3773
                                            newY = (point[1] + nextY) / 2;
3774
                                    }
3775
                                    resultPoint = new double[] { resultPoint[0], newY };
3776
                                }
3777
                            }
3778
                        }
3779
                        break;
3780
                    }
3781
                }
3782
            }
3783

    
3784
            x = resultPoint[0];
3785
            y = resultPoint[1];
3786

    
3787
            return targetConnector;
3788
        }
3789

    
3790
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3791
        {
3792
            LMConnector result = null;
3793
            List<LMConnector> connectors = new List<LMConnector>();
3794
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3795

    
3796
            if (modelItem != null)
3797
            {
3798
                foreach (LMRepresentation rep in modelItem.Representations)
3799
                {
3800
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3801
                        connectors.Add(dataSource.GetConnector(rep.Id));
3802
                }
3803

    
3804
                ReleaseCOMObjects(modelItem);
3805
            }
3806

    
3807
            if (connectors.Count == 1)
3808
                result = connectors[0];
3809
            else
3810
                foreach (var item in connectors)
3811
                    ReleaseCOMObjects(item);
3812

    
3813
            return result;
3814
        }
3815

    
3816
        private int GetConnectorCount(string modelItemID)
3817
        {
3818
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3819
            int result = 0;
3820
            if (modelItem != null)
3821
            {
3822
                foreach (LMRepresentation rep in modelItem.Representations)
3823
                {
3824
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3825
                        result++;
3826
                    ReleaseCOMObjects(rep);
3827
                }
3828
                ReleaseCOMObjects(modelItem);
3829
            }
3830

    
3831
            return result;
3832
        }
3833

    
3834
        public List<string> GetRepresentations(string modelItemID)
3835
        {
3836
            List<string> result = new List<string>(); ;
3837
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3838
            if (modelItem != null)
3839
            {
3840
                foreach (LMRepresentation rep in modelItem.Representations)
3841
                {
3842
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3843
                        result.Add(rep.Id);
3844
                }
3845
                ReleaseCOMObjects(modelItem);
3846
            }
3847

    
3848
            return result;
3849
        }
3850

    
3851
        /// <summary>
3852
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3853
        /// </summary>
3854
        /// <param name="lineNumber"></param>
3855
        private void LineNumberModelingOnlyOne(Line line)
3856
        {
3857
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3858
            if (lineNumber != null)
3859
            {
3860
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3861
                if (connectedLMConnector != null)
3862
                {
3863
                    double x = 0;
3864
                    double y = 0;
3865
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3866

    
3867
                    Array points = new double[] { 0, x, y };
3868
                    lineNumber.SPPID.SPPID_X = x;
3869
                    lineNumber.SPPID.SPPID_Y = y;
3870
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3871

    
3872
                    if (_LmLabelPresist != null)
3873
                    {
3874
                        _LmLabelPresist.Commit();
3875
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3876
                        ReleaseCOMObjects(_LmLabelPresist);
3877
                    }
3878
                }
3879
            }
3880
        }
3881

    
3882
        private void LineNumberModeling(LineNumber lineNumber)
3883
        {
3884
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3885
            if (line != null)
3886
            {
3887
                double x = 0;
3888
                double y = 0;
3889
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3890

    
3891
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3892
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3893
                if (connectedLMConnector != null)
3894
                {
3895
                    Array points = new double[] { 0, x, y };
3896
                    lineNumber.SPPID.SPPID_X = x;
3897
                    lineNumber.SPPID.SPPID_Y = y;
3898
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3899

    
3900
                    if (_LmLabelPresist != null)
3901
                    {
3902
                        _LmLabelPresist.Commit();
3903
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3904
                        ReleaseCOMObjects(_LmLabelPresist);
3905
                    }
3906
                }
3907

    
3908
                foreach (var item in connectorVertices)
3909
                    ReleaseCOMObjects(item.Key);
3910
            }
3911
        }
3912
        private void LineNumberCorrectModeling(LineNumber lineNumber)
3913
        {
3914
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3915
            if (line == null || line.SPPID.Vertices == null)
3916
                return;
3917

    
3918
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
3919
            {
3920
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
3921
                if (removeLabel != null)
3922
                {
3923
                    GridSetting gridSetting = GridSetting.GetInstance();
3924
                    double[] labelRange = null;
3925
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
3926
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
3927
                    List<double[]> vertices = GetConnectorVertices(connector);
3928

    
3929
                    double[] resultStart = null;
3930
                    double[] resultEnd = null;
3931
                    double distance = double.MaxValue;
3932
                    for (int i = 0; i < vertices.Count - 1; i++)
3933
                    {
3934
                        double[] startPoint = vertices[i];
3935
                        double[] endPoint = vertices[i + 1];
3936
                        foreach (var item in line.SPPID.Vertices)
3937
                        {
3938
                            double[] lineStartPoint = item[0];
3939
                            double[] lineEndPoint = item[item.Count - 1];
3940

    
3941
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
3942
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
3943
                            if (tempDistance < distance)
3944
                            {
3945
                                distance = tempDistance;
3946
                                resultStart = startPoint;
3947
                                resultEnd = endPoint;
3948
                            }
3949
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
3950
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
3951
                            if (tempDistance < distance)
3952
                            {
3953
                                distance = tempDistance;
3954
                                resultStart = startPoint;
3955
                                resultEnd = endPoint;
3956
                            }
3957
                        }
3958
                    }
3959

    
3960
                    if (resultStart != null && resultEnd != null)
3961
                    {
3962
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
3963
                        double lineStartX = 0;
3964
                        double lineStartY = 0;
3965
                        double lineEndX = 0;
3966
                        double lineEndY = 0;
3967
                        double lineNumberX = 0;
3968
                        double lineNumberY = 0;
3969
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
3970
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
3971

    
3972
                        double lineX = (lineStartX + lineEndX) / 2;
3973
                        double lineY = (lineStartY + lineEndY) / 2;
3974
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
3975
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
3976

    
3977
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
3978
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
3979
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
3980
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
3981

    
3982
                        double offsetX = 0;
3983
                        double offsetY = 0;
3984
                        if (slope == SlopeType.HORIZONTAL)
3985
                        {
3986
                            // Line Number 아래
3987
                            if (lineY < lineNumberY)
3988
                            {
3989
                                offsetX = labelCenterX - SPPIDCenterX;
3990
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
3991
                                MoveLineNumber(lineNumber, offsetX, offsetY);
3992
                            }
3993
                            // Line Number 위
3994
                            else
3995
                            {
3996
                                offsetX = labelCenterX - SPPIDCenterX;
3997
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
3998
                                MoveLineNumber(lineNumber, offsetX, offsetY);
3999
                            }
4000
                        }
4001
                        else if (slope == SlopeType.VERTICAL)
4002
                        {
4003
                            // Line Number 오르쪽
4004
                            if (lineX < lineNumberX)
4005
                            {
4006
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4007
                                offsetY = labelCenterY - SPPIDCenterY;
4008
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4009
                            }
4010
                            // Line Number 왼쪽
4011
                            else
4012
                            {
4013
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4014
                                offsetY = labelCenterY - SPPIDCenterY;
4015
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4016
                            }
4017
                        }
4018

    
4019
                        if (offsetY != 0 && offsetY != 0)
4020
                        {
4021
                            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4022
                            Array points = new double[] { 0, lineNumber.SPPID.SPPID_X, lineNumber.SPPID.SPPID_Y };
4023
                            LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connector.AsLMRepresentation(), IsLeaderVisible: false);
4024

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

    
4034
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4035
                        {
4036
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4037
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4038
                        }
4039
                    }
4040

    
4041

    
4042
                    ReleaseCOMObjects(connector);
4043
                    connector = null;
4044
                }
4045

    
4046
                ReleaseCOMObjects(removeLabel);
4047
                removeLabel = null;
4048
            }
4049
        }
4050
        /// <summary>
4051
        /// Flow Mark Modeling
4052
        /// </summary>
4053
        /// <param name="line"></param>
4054
        private void FlowMarkModeling(Line line)
4055
        {
4056
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4057
            {
4058
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4059
                if (connector != null)
4060
                {
4061
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4062
                    List<double[]> vertices = GetConnectorVertices(connector);
4063
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4064
                    double[] point = vertices[vertices.Count - 1];
4065
                    Array array = new double[] { 0, point[0], point[1] };
4066
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4067
                    if (_LMLabelPersist != null)
4068
                    {
4069
                        _LMLabelPersist.Commit();
4070
                        ReleaseCOMObjects(_LMLabelPersist);
4071
                    }
4072
                        
4073
                }
4074
            }
4075
        }
4076

    
4077
        /// <summary>
4078
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4079
        /// </summary>
4080
        /// <param name="lineNumber"></param>
4081
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4082
        {
4083
            foreach (LineRun run in lineNumber.RUNS)
4084
            {
4085
                foreach (var item in run.RUNITEMS)
4086
                {
4087
                    if (item.GetType() == typeof(Symbol))
4088
                    {
4089
                        Symbol symbol = item as Symbol;
4090
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4091
                        if (_LMSymbol != null)
4092
                        {
4093
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4094

    
4095
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4096
                            {
4097
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4098
                                {
4099
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4100
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4101
                                    {
4102
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4103
                                        if (_LMAAttribute != null)
4104
                                        {
4105
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4106
                                                _LMAAttribute.set_Value(attribute.VALUE);
4107
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4108
                                                _LMAAttribute.set_Value(attribute.VALUE);
4109
                                        }
4110
                                    }
4111
                                }
4112
                                _LMModelItem.Commit();
4113
                            }
4114
                            if (_LMModelItem != null)
4115
                                ReleaseCOMObjects(_LMModelItem);
4116
                        }
4117
                        if (_LMSymbol != null)
4118
                            ReleaseCOMObjects(_LMSymbol);
4119
                    }
4120
                    else if (item.GetType() == typeof(Line))
4121
                    {
4122
                        Line line = item as Line;
4123
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4124
                        {
4125
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4126
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4127
                            {
4128
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4129
                                {
4130
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4131
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4132
                                    {
4133
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4134
                                        if (_LMAAttribute != null)
4135
                                        {
4136
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4137
                                                _LMAAttribute.set_Value(attribute.VALUE);
4138
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4139
                                                _LMAAttribute.set_Value(attribute.VALUE);
4140

    
4141
                                        }
4142
                                    }
4143
                                }
4144
                                _LMModelItem.Commit();
4145
                            }
4146
                            if (_LMModelItem != null)
4147
                                ReleaseCOMObjects(_LMModelItem);
4148
                            endLine.Add(line.SPPID.ModelItemId);
4149
                        }
4150
                    }
4151
                }
4152
            }
4153
        }
4154

    
4155
        /// <summary>
4156
        /// Symbol Attribute 입력 메서드
4157
        /// </summary>
4158
        /// <param name="item"></param>
4159
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4160
        {
4161
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4162
            string sRep = null;
4163
            if (targetItem.GetType() == typeof(Symbol))
4164
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4165
            else if (targetItem.GetType() == typeof(Equipment))
4166
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4167

    
4168
            if (!string.IsNullOrEmpty(sRep))
4169
            {
4170
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4171
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4172
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4173
                
4174
                foreach (var item in targetAttributes)
4175
                {
4176
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4177
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4178
                    {
4179
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4180
                        if (_Attribute != null)
4181
                        {
4182
                            //object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
4183
                            //if (associItem != null)
4184
                            //{
4185
                            //    if (associItem.GetType() == typeof(Text))
4186
                            //    {
4187
                            //        Text text = associItem as Text;
4188
                            //        text.SPPID.RepresentationId = "Attribute";
4189
                            //    }
4190
                            //    else if (associItem.GetType() == typeof(Note))
4191
                            //    {
4192
                            //        Note note = associItem as Note;
4193
                            //        note.SPPID.RepresentationId = "Attribute";
4194
                            //    }
4195
                            //}
4196
                            _Attribute.set_Value(item.VALUE);
4197
                            // OPC 일경우 Attribute 저장
4198
                            if (targetItem.GetType() == typeof(Symbol))
4199
                            {
4200
                                Symbol symbol = targetItem as Symbol;
4201
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4202
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4203
                            }
4204
                        }
4205
                    }
4206
                }
4207
                _LMModelItem.Commit();
4208

    
4209
                ReleaseCOMObjects(_Attributes);
4210
                ReleaseCOMObjects(_LMModelItem);
4211
                ReleaseCOMObjects(_LMSymbol);
4212
            }
4213
        }
4214

    
4215
        /// <summary>
4216
        /// Input SpecBreak Attribute
4217
        /// </summary>
4218
        /// <param name="specBreak"></param>
4219
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4220
        {
4221
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4222
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4223

    
4224
            if (upStreamObj != null &&
4225
                downStreamObj != null)
4226
            {
4227
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4228

    
4229
                if (targetLMConnector != null)
4230
                {
4231
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4232
                    {
4233
                        string symbolPath = _LMLabelPersist.get_FileName();
4234
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4235
                        if (mapping != null)
4236
                        {
4237
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4238
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4239
                            {
4240
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4241
                                if (values.Length == 2)
4242
                                {
4243
                                    string upStreamValue = values[0];
4244
                                    string downStreamValue = values[1];
4245

    
4246
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4247
                                }
4248
                            }
4249
                        }
4250
                    }
4251

    
4252
                    ReleaseCOMObjects(targetLMConnector);
4253
                }
4254
            }
4255

    
4256

    
4257
            #region 내부에서만 쓰는 메서드
4258
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4259
            {
4260
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4261
                Line upStreamLine = _upStreamObj as Line;
4262
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4263
                Line downStreamLine = _downStreamObj as Line;
4264
                // 둘다 Line일 경우
4265
                if (upStreamLine != null && downStreamLine != null)
4266
                {
4267
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4268
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4269
                }
4270
                // 둘다 Symbol일 경우
4271
                else if (upStreamSymbol != null && downStreamSymbol != null)
4272
                {
4273
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4274
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4275
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4276

    
4277
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4278
                    {
4279
                        if (connector.get_ItemStatus() != "Active")
4280
                            continue;
4281

    
4282
                        if (connector.Id != zeroLenthConnector.Id)
4283
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4284
                    }
4285

    
4286
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4287
                    {
4288
                        if (connector.get_ItemStatus() != "Active")
4289
                            continue;
4290

    
4291
                        if (connector.Id != zeroLenthConnector.Id)
4292
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4293
                    }
4294

    
4295
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4296
                    {
4297
                        if (connector.get_ItemStatus() != "Active")
4298
                            continue;
4299

    
4300
                        if (connector.Id != zeroLenthConnector.Id)
4301
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4302
                    }
4303

    
4304
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4305
                    {
4306
                        if (connector.get_ItemStatus() != "Active")
4307
                            continue;
4308

    
4309
                        if (connector.Id != zeroLenthConnector.Id)
4310
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4311
                    }
4312

    
4313
                    ReleaseCOMObjects(zeroLenthConnector);
4314
                    ReleaseCOMObjects(upStreamLMSymbol);
4315
                    ReleaseCOMObjects(downStreamLMSymbol);
4316
                }
4317
                else if (upStreamSymbol != null && downStreamLine != null)
4318
                {
4319
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4320
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4321
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4322

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

    
4328
                        if (connector.Id == zeroLenthConnector.Id)
4329
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4330
                    }
4331

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

    
4337
                        if (connector.Id == zeroLenthConnector.Id)
4338
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4339
                    }
4340

    
4341
                    ReleaseCOMObjects(zeroLenthConnector);
4342
                    ReleaseCOMObjects(upStreamLMSymbol);
4343
                }
4344
                else if (upStreamLine != null && downStreamSymbol != null)
4345
                {
4346
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4347
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4348
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4349

    
4350
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4351
                    {
4352
                        if (connector.get_ItemStatus() != "Active")
4353
                            continue;
4354

    
4355
                        if (connector.Id == zeroLenthConnector.Id)
4356
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4357
                    }
4358

    
4359
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4360
                    {
4361
                        if (connector.get_ItemStatus() != "Active")
4362
                            continue;
4363

    
4364
                        if (connector.Id == zeroLenthConnector.Id)
4365
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4366
                    }
4367

    
4368
                    ReleaseCOMObjects(zeroLenthConnector);
4369
                    ReleaseCOMObjects(downStreamLMSymbol);
4370
                }
4371
            }
4372

    
4373
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4374
            {
4375
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4376
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4377
                {
4378
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4379
                    if (_LMAAttribute != null)
4380
                    {
4381
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4382
                            _LMAAttribute.set_Value(value);
4383
                        else if (_LMAAttribute.get_Value() != value)
4384
                            _LMAAttribute.set_Value(value);
4385
                    }
4386

    
4387
                    _LMModelItem.Commit();
4388
                }
4389
                if (_LMModelItem != null)
4390
                    ReleaseCOMObjects(_LMModelItem);
4391
            }
4392

    
4393
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4394
            {
4395
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4396
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4397
                {
4398
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4399
                    if (_LMAAttribute != null)
4400
                    {
4401
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4402
                            _LMAAttribute.set_Value(value);
4403
                        else if (_LMAAttribute.get_Value() != value)
4404
                            _LMAAttribute.set_Value(value);
4405
                    }
4406

    
4407
                    _LMModelItem.Commit();
4408
                }
4409
                if (_LMModelItem != null)
4410
                    ReleaseCOMObjects(_LMModelItem);
4411
            }
4412
            #endregion
4413
        }
4414

    
4415
        private void InputEndBreakAttribute(EndBreak endBreak)
4416
        {
4417
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4418
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4419

    
4420
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4421
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4422
            {
4423
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4424
                if (labelPersist != null)
4425
                {
4426
                    LMRepresentation representation = labelPersist.RepresentationObject;
4427
                    if (representation != null)
4428
                    {
4429
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4430
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4431
                        string modelItemID = connector.ModelItemID;
4432
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4433
                        {
4434
                            List<string> modelItemIDs = new List<string>();
4435
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4436
                            {
4437
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4438
                                foreach (LMConnector item in symbol.Connect1Connectors)
4439
                                {
4440
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4441
                                        modelItemIDs.Add(item.ModelItemID);
4442
                                    ReleaseCOMObjects(item);
4443
                                }
4444
                                foreach (LMConnector item in symbol.Connect2Connectors)
4445
                                {
4446
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4447
                                        modelItemIDs.Add(item.ModelItemID);
4448
                                    ReleaseCOMObjects(item);
4449
                                }
4450
                                ReleaseCOMObjects(symbol);
4451
                                symbol = null;
4452
                            }
4453
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4454
                            {
4455
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4456
                                foreach (LMConnector item in symbol.Connect1Connectors)
4457
                                {
4458
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4459
                                        modelItemIDs.Add(item.ModelItemID);
4460
                                    ReleaseCOMObjects(item);
4461
                                }
4462
                                foreach (LMConnector item in symbol.Connect2Connectors)
4463
                                {
4464
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4465
                                        modelItemIDs.Add(item.ModelItemID);
4466
                                    ReleaseCOMObjects(item);
4467
                                }
4468
                                ReleaseCOMObjects(symbol);
4469
                                symbol = null;
4470
                            }
4471

    
4472
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4473
                            if (modelItemIDs.Count == 1)
4474
                            {
4475
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4476
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4477
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4478
                                {
4479
                                    bool result = false;
4480
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4481
                                    {
4482
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4483
                                            result = true;
4484
                                        ReleaseCOMObjects(loop);
4485
                                    }
4486

    
4487
                                    if (result)
4488
                                    {
4489
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4490
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4491
                                        ZeroLengthModelItem.Commit();
4492
                                    }
4493
                                    else
4494
                                    {
4495
                                        List<string> loopModelItems = new List<string>();
4496
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
4497
                                        {
4498
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
4499
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4500
                                            {
4501
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4502
                                                    loopModelItems.Add(loop.ModelItemID);
4503
                                                ReleaseCOMObjects(loop);
4504
                                            }
4505
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4506
                                            {
4507
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4508
                                                    loopModelItems.Add(loop.ModelItemID);
4509
                                                ReleaseCOMObjects(loop);
4510
                                            }
4511
                                            ReleaseCOMObjects(_symbol);
4512
                                            _symbol = null;
4513
                                        }
4514
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
4515
                                        {
4516
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
4517
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4518
                                            {
4519
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4520
                                                    loopModelItems.Add(loop.ModelItemID);
4521
                                                ReleaseCOMObjects(loop);
4522
                                            }
4523
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4524
                                            {
4525
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4526
                                                    loopModelItems.Add(loop.ModelItemID);
4527
                                                ReleaseCOMObjects(loop);
4528
                                            }
4529
                                            ReleaseCOMObjects(_symbol);
4530
                                            _symbol = null;
4531
                                        }
4532

    
4533
                                        loopModelItems = loopModelItems.Distinct().ToList();
4534
                                        if (loopModelItems.Count == 1)
4535
                                        {
4536
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
4537
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
4538
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
4539
                                            modelItem.Commit();
4540
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4541
                                            ZeroLengthModelItem.Commit();
4542

    
4543
                                            ReleaseCOMObjects(loopModelItem);
4544
                                            loopModelItem = null;
4545
                                        }
4546
                                    }
4547
                                }
4548
                                else
4549
                                {
4550
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4551
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4552
                                    ZeroLengthModelItem.Commit();
4553
                                }
4554
                                ReleaseCOMObjects(modelItem);
4555
                                modelItem = null;
4556
                                ReleaseCOMObjects(onlyOne);
4557
                                onlyOne = null;
4558
                            }
4559
                        }
4560
                        ReleaseCOMObjects(connector);
4561
                        connector = null;
4562
                        ReleaseCOMObjects(ZeroLengthModelItem);
4563
                        ZeroLengthModelItem = null;
4564
                    }
4565
                    ReleaseCOMObjects(representation);
4566
                    representation = null;
4567
                }
4568
                ReleaseCOMObjects(labelPersist);
4569
                labelPersist = null;
4570
            }
4571
        }
4572

    
4573
        /// <summary>
4574
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
4575
        /// </summary>
4576
        /// <param name="text"></param>
4577
        private void NormalTextModeling(Text text)
4578
        {
4579
            LMSymbol _LMSymbol = null;
4580

    
4581
            LMItemNote _LMItemNote = null;
4582
            LMAAttribute _LMAAttribute = null;
4583

    
4584
            double x = 0;
4585
            double y = 0;
4586
            double angle = text.ANGLE;
4587
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
4588

    
4589
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4590
            text.SPPID.SPPID_X = x;
4591
            text.SPPID.SPPID_Y = y;
4592

    
4593
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
4594
            if (_LMSymbol != null)
4595
            {
4596
                _LMSymbol.Commit();
4597
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4598
                if (_LMItemNote != null)
4599
                {
4600
                    _LMItemNote.Commit();
4601
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4602
                    if (_LMAAttribute != null)
4603
                    {
4604
                        _LMAAttribute.set_Value(text.VALUE);
4605
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4606
                        _LMItemNote.Commit();
4607

    
4608

    
4609
                        double[] range = null;
4610
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4611
                        {
4612
                            double[] temp = null;
4613
                            GetSPPIDSymbolRange(labelPersist, ref temp);
4614
                            if (temp != null)
4615
                            {
4616
                                if (range == null)
4617
                                    range = temp;
4618
                                else
4619
                                {
4620
                                    range = new double[] {
4621
                                            Math.Min(range[0], temp[0]),
4622
                                            Math.Min(range[1], temp[1]),
4623
                                            Math.Max(range[2], temp[2]),
4624
                                            Math.Max(range[3], temp[3])
4625
                                        };
4626
                                }
4627
                            }
4628
                        }
4629
                        text.SPPID.Range = range;
4630

    
4631
                        if (_LMAAttribute != null)
4632
                            ReleaseCOMObjects(_LMAAttribute);
4633
                        if (_LMItemNote != null)
4634
                            ReleaseCOMObjects(_LMItemNote);
4635
                    }
4636

    
4637
                    TextCorrectModeling(text);
4638
                }
4639
            }
4640
            if (_LMSymbol != null)
4641
                ReleaseCOMObjects(_LMSymbol);
4642
        }
4643

    
4644
        private void AssociationTextModeling(Text text)
4645
        {
4646
            LMSymbol _LMSymbol = null;
4647
            LMConnector connectedLMConnector = null;
4648
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4649
            if (owner != null && owner.GetType() == typeof(Symbol))
4650
            {
4651
                Symbol symbol = owner as Symbol;
4652
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4653
                if (_LMSymbol != null)
4654
                {
4655
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4656
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4657
                    {
4658
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4659

    
4660
                        if (mapping != null)
4661
                        {
4662
                            double x = 0;
4663
                            double y = 0;
4664

    
4665
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4666
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4667
                            Array array = new double[] { 0, x, y };
4668
                            text.SPPID.SPPID_X = x;
4669
                            text.SPPID.SPPID_Y = y;
4670
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4671
                            if (_LMLabelPersist != null)
4672
                            {
4673
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4674
                                _LMLabelPersist.Commit();
4675
                                ReleaseCOMObjects(_LMLabelPersist);
4676
                            }
4677
                        }
4678
                    }
4679
                }
4680
            }
4681
            else if (owner != null && owner.GetType() == typeof(Line))
4682
            {
4683
                Line line = owner as Line;
4684
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4685
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
4686

    
4687
                if (connectedLMConnector != null)
4688
                {
4689
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4690
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4691
                    {
4692
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4693

    
4694
                        if (mapping != null)
4695
                        {
4696
                            double x = 0;
4697
                            double y = 0;
4698
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4699
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4700
                            Array array = new double[] { 0, x, y };
4701

    
4702
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4703
                            if (_LMLabelPersist != null)
4704
                            {
4705
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4706
                                _LMLabelPersist.Commit();
4707
                                ReleaseCOMObjects(_LMLabelPersist);
4708
                            }
4709
                        }
4710
                    }
4711
                }
4712
            }
4713
            if (_LMSymbol != null)
4714
                ReleaseCOMObjects(_LMSymbol);
4715
        }
4716

    
4717
        private void TextCorrectModeling(Text text)
4718
        {
4719
            if (text.SPPID.Range == null)
4720
                return;
4721

    
4722
            bool needRemodeling = false;
4723
            bool loop = true;
4724
            GridSetting gridSetting = GridSetting.GetInstance();
4725
            while (loop)
4726
            {
4727
                loop = false;
4728
                foreach (var overlapText in document.TEXTINFOS)
4729
                {
4730
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
4731
                        continue;
4732

    
4733
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
4734
                    {
4735
                        double percentX = 0;
4736
                        double percentY = 0;
4737
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
4738
                        {
4739
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
4740
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
4741
                        }
4742
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
4743
                        {
4744
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
4745
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
4746
                        }
4747

    
4748
                        double tempX = 0;
4749
                        double tempY = 0;
4750
                        bool overlapX = false;
4751
                        bool overlapY = false;
4752
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4753
                        if (percentX >= percentY)
4754
                        {
4755
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4756
                            double move = gridSetting.Length * count;
4757
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
4758
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
4759
                            needRemodeling = true;
4760
                            loop = true;
4761
                        }
4762
                        else
4763
                        {
4764
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4765
                            double move = gridSetting.Length * count;
4766
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
4767
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
4768
                            needRemodeling = true;
4769
                            loop = true;
4770
                        }
4771
                    }
4772
                }
4773
            }
4774
            
4775

    
4776
            if (needRemodeling)
4777
            {
4778
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
4779
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4780
                text.SPPID.RepresentationId = null;
4781

    
4782
                LMItemNote _LMItemNote = null;
4783
                LMAAttribute _LMAAttribute = null;
4784
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
4785
                if (_LMSymbol != null)
4786
                {
4787
                    _LMSymbol.Commit();
4788
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4789
                    if (_LMItemNote != null)
4790
                    {
4791
                        _LMItemNote.Commit();
4792
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4793
                        if (_LMAAttribute != null)
4794
                        {
4795
                            _LMAAttribute.set_Value(text.VALUE);
4796
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4797
                            _LMItemNote.Commit();
4798

    
4799
                            ReleaseCOMObjects(_LMAAttribute);
4800
                            ReleaseCOMObjects(_LMItemNote);
4801
                        }
4802
                    }
4803
                }
4804

    
4805
                ReleaseCOMObjects(symbol);
4806
                symbol = null;
4807
                ReleaseCOMObjects(_LMItemNote);
4808
                _LMItemNote = null;
4809
                ReleaseCOMObjects(_LMAAttribute);
4810
                _LMAAttribute = null;
4811
                ReleaseCOMObjects(_LMSymbol);
4812
                _LMSymbol = null;
4813
            }
4814
        }
4815

    
4816
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
4817
        {
4818
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
4819
            {
4820
                List<Text> texts = new List<Text>();
4821
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
4822
                LMRepresentation representation = targetLabel.RepresentationObject;
4823
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
4824
                if (targetLabel.RepresentationObject != null && symbol != null)
4825
                {
4826
                    double[] symbolRange = null;
4827
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
4828
                    if (symbolRange != null)
4829
                    {
4830
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
4831
                        {
4832
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
4833
                            if (findText != null)
4834
                            {
4835
                                double[] range = null;
4836
                                GetSPPIDSymbolRange(labelPersist, ref range);
4837
                                findText.SPPID.Range = range;
4838
                                texts.Add(findText);
4839
                            }
4840

    
4841
                            ReleaseCOMObjects(labelPersist);
4842
                        }
4843

    
4844
                        if (texts.Count > 0)
4845
                        {
4846
                            #region Sort Text By Y
4847
                            texts.Sort(SortTextByY);
4848
                            int SortTextByY(Text a, Text b)
4849
                            {
4850
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
4851
                            }
4852
                            #endregion
4853

    
4854
                            #region 첫번째 Text로 기준 맞춤
4855
                            for (int i = 0; i < texts.Count; i++)
4856
                            {
4857
                                if (i != 0)
4858
                                {
4859
                                    Text currentText = texts[i];
4860
                                    Text prevText = texts[i - 1];
4861
                                    double minY = prevText.SPPID.Range[1];
4862
                                    double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
4863
                                    double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
4864
                                    double _gapX = centerX - centerPrevX;
4865
                                    double _gapY = currentText.SPPID.Range[3] - minY;
4866
                                    MoveText(currentText, _gapX, _gapY);
4867
                                }
4868
                            }
4869
                            List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
4870
                            List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
4871
                            List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
4872
                            List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
4873
                            rangeMinX.Sort();
4874
                            rangeMinY.Sort();
4875
                            rangeMaxX.Sort();
4876
                            rangeMaxY.Sort();
4877
                            double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
4878
                            double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
4879
                            #endregion
4880

    
4881
                            Text correctBySymbol = texts[0];
4882
                            double textCenterX = (text.X1 + text.X2) / 2;
4883
                            double textCenterY = (text.Y1 + text.Y2) / 2;
4884
                            double originX = 0;
4885
                            double originY = 0;
4886
                            SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
4887
                            double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
4888
                            double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
4889
                            double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
4890

    
4891
                            double gapX = 0;
4892
                            double gapY = 0;
4893
                            if (angle < 45)
4894
                            {
4895
                                // Text 오른쪽
4896
                                if (textCenterX > originX)
4897
                                {
4898
                                    gapX = rangeMinX[0] - symbolRange[2];
4899
                                    gapY = allTextCenterY - symbolCenterY;
4900
                                }
4901
                                // Text 왼쪽
4902
                                else
4903
                                {
4904
                                    gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
4905
                                    gapY = allTextCenterY - symbolCenterY;
4906
                                }
4907
                            }
4908
                            else
4909
                            {
4910
                                // Text 아래쪽
4911
                                if (textCenterY > originY)
4912
                                {
4913
                                    gapX = allTextCenterX - symbolCenterX;
4914
                                    gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
4915
                                }
4916
                                // Text 위쪽
4917
                                else
4918
                                {
4919
                                    gapX = allTextCenterX - symbolCenterX;
4920
                                    gapY = rangeMinY[0] - symbolRange[3];
4921
                                }
4922
                            }
4923

    
4924
                            foreach (var item in texts)
4925
                            {
4926
                                MoveText(item, gapX, gapY);
4927
                                RemodelingAssociationText(item);
4928
                            }
4929
                        }
4930
                    }
4931
                }
4932

    
4933
                void MoveText(Text moveText, double x, double y)
4934
                {
4935
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
4936
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
4937
                    moveText.SPPID.Range = new double[] {
4938
                        moveText.SPPID.Range[0] - x,
4939
                        moveText.SPPID.Range[1]- y,
4940
                        moveText.SPPID.Range[2]- x,
4941
                        moveText.SPPID.Range[3]- y
4942
                    };
4943
                }
4944

    
4945
                endTexts.AddRange(texts);
4946

    
4947
                ReleaseCOMObjects(targetLabel);
4948
                targetLabel = null;
4949
                ReleaseCOMObjects(representation);
4950
                representation = null;
4951
            }
4952
        }
4953

    
4954
        private void RemodelingAssociationText(Text text)
4955
        {
4956
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
4957
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4958
            removeLabel.Commit();
4959
            ReleaseCOMObjects(removeLabel);
4960
            removeLabel = null;
4961

    
4962
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4963
            if (owner != null && owner.GetType() == typeof(Symbol))
4964
            {
4965
                Symbol symbol = owner as Symbol;
4966
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4967
                if (_LMSymbol != null)
4968
                {
4969
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4970
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4971
                    {
4972
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4973

    
4974
                        if (mapping != null)
4975
                        {
4976
                            double x = 0;
4977
                            double y = 0;
4978

    
4979
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
4980
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4981
                            if (_LMLabelPersist != null)
4982
                            {
4983
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4984
                                _LMLabelPersist.Commit();
4985
                            }
4986
                            ReleaseCOMObjects(_LMLabelPersist);
4987
                            _LMLabelPersist = null;
4988
                        }
4989
                    }
4990
                }
4991
                ReleaseCOMObjects(_LMSymbol);
4992
                _LMSymbol = null;
4993
            }
4994
        }
4995

    
4996
        /// <summary>
4997
        /// Note Modeling
4998
        /// </summary>
4999
        /// <param name="note"></param>
5000
        private void NoteModeling(Note note, List<Note> correctList)
5001
        {
5002
            LMSymbol _LMSymbol = null;
5003
            LMItemNote _LMItemNote = null;
5004
            LMAAttribute _LMAAttribute = null;
5005

    
5006
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5007
            {
5008
                double x = 0;
5009
                double y = 0;
5010

    
5011
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5012
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5013
                note.SPPID.SPPID_X = x;
5014
                note.SPPID.SPPID_Y = y;
5015

    
5016
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5017
                if (_LMSymbol != null)
5018
                {
5019
                    _LMSymbol.Commit();
5020
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5021
                    if (_LMItemNote != null)
5022
                    {
5023
                        _LMItemNote.Commit();
5024
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5025
                        if (_LMAAttribute != null)
5026
                        {
5027
                            _LMAAttribute.set_Value(note.VALUE);
5028
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5029

    
5030
                            double[] range = null;
5031
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5032
                            {
5033
                                double[] temp = null;
5034
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5035
                                if (temp != null)
5036
                                {
5037
                                    if (range == null)
5038
                                        range = temp;
5039
                                    else
5040
                                    {
5041
                                        range = new double[] {
5042
                                            Math.Min(range[0], temp[0]),
5043
                                            Math.Min(range[1], temp[1]),
5044
                                            Math.Max(range[2], temp[2]),
5045
                                            Math.Max(range[3], temp[3])
5046
                                        };
5047
                                    }
5048
                                }
5049
                            }
5050
                            if (range != null)
5051
                                correctList.Add(note);
5052
                            note.SPPID.Range = range;
5053

    
5054

    
5055
                            _LMItemNote.Commit();
5056
                        }
5057
                    }
5058
                }
5059
            }
5060

    
5061
            if (_LMAAttribute != null)
5062
                ReleaseCOMObjects(_LMAAttribute);
5063
            if (_LMItemNote != null)
5064
                ReleaseCOMObjects(_LMItemNote);
5065
            if (_LMSymbol != null)
5066
                ReleaseCOMObjects(_LMSymbol);
5067
        }
5068

    
5069
        private void NoteCorrectModeling(Note note, List<Note> endList)
5070
        {
5071
            bool needRemodeling = false;
5072
            bool loop = true;
5073
            GridSetting gridSetting = GridSetting.GetInstance();
5074
            while (loop)
5075
            {
5076
                loop = false;
5077
                foreach (var overlap in endList)
5078
                {
5079
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5080
                    {
5081
                        double tempX = 0;
5082
                        double tempY = 0;
5083
                        bool overlapX = false;
5084
                        bool overlapY = false;
5085
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5086
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5087
                        if (overlapY && angle >= 45)
5088
                        {
5089
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5090
                            double move = gridSetting.Length * count;
5091
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5092
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5093
                            needRemodeling = true;
5094
                            loop = true;
5095
                        }
5096
                        if (overlapX && angle <= 45)
5097
                        {
5098
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5099
                            double move = gridSetting.Length * count;
5100
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5101
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5102
                            needRemodeling = true;
5103
                            loop = true;
5104
                        }
5105
                    }
5106
                }
5107
            }
5108

    
5109

    
5110
            if (needRemodeling)
5111
            {
5112
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5113
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5114
                note.SPPID.RepresentationId = null;
5115

    
5116
                LMItemNote _LMItemNote = null;
5117
                LMAAttribute _LMAAttribute = null;
5118
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5119
                if (_LMSymbol != null)
5120
                {
5121
                    _LMSymbol.Commit();
5122
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5123
                    if (_LMItemNote != null)
5124
                    {
5125
                        _LMItemNote.Commit();
5126
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5127
                        if (_LMAAttribute != null)
5128
                        {
5129
                            _LMAAttribute.set_Value(note.VALUE);
5130
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5131
                            _LMItemNote.Commit();
5132

    
5133
                            ReleaseCOMObjects(_LMAAttribute);
5134
                            ReleaseCOMObjects(_LMItemNote);
5135
                        }
5136
                    }
5137
                }
5138

    
5139
                ReleaseCOMObjects(symbol);
5140
                symbol = null;
5141
                ReleaseCOMObjects(_LMItemNote);
5142
                _LMItemNote = null;
5143
                ReleaseCOMObjects(_LMAAttribute);
5144
                _LMAAttribute = null;
5145
                ReleaseCOMObjects(_LMSymbol);
5146
                _LMSymbol = null;
5147
            }
5148

    
5149
            endList.Add(note);
5150
        }
5151

    
5152
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5153
        {
5154
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5155
            if (modelItem != null)
5156
            {
5157
                foreach (LMRepresentation rep in modelItem.Representations)
5158
                {
5159
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5160
                    {
5161
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5162
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5163
                        {
5164
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5165
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5166
                            if (modelItemIds.Count == 1)
5167
                            {
5168
                                string joinModelItemId = modelItemIds[0];
5169
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
5170
                                if (survivorId != null)
5171
                                    break;
5172
                            }
5173
                        }
5174
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5175
                        {
5176
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5177
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5178
                            if (modelItemIds.Count == 1)
5179
                            {
5180
                                string joinModelItemId = modelItemIds[0];
5181
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
5182
                                if (survivorId != null)
5183
                                    break;
5184
                            }
5185
                        }
5186
                    }
5187
                }
5188
            }
5189
        }
5190

    
5191
        /// <summary>
5192
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5193
        /// </summary>
5194
        /// <param name="x"></param>
5195
        /// <param name="y"></param>
5196
        /// <param name="originX"></param>
5197
        /// <param name="originY"></param>
5198
        /// <param name="SPPIDLabelLocation"></param>
5199
        /// <param name="location"></param>
5200
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5201
        {
5202
            if (location == Location.None)
5203
            {
5204
                x = originX;
5205
                y = originY;
5206
            }
5207
            else
5208
            {
5209
                if (location.HasFlag(Location.Center))
5210
                {
5211
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5212
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5213
                }
5214

    
5215
                if (location.HasFlag(Location.Left))
5216
                    x = SPPIDLabelLocation.X1;
5217
                else if (location.HasFlag(Location.Right))
5218
                    x = SPPIDLabelLocation.X2;
5219

    
5220
                if (location.HasFlag(Location.Down))
5221
                    y = SPPIDLabelLocation.Y1;
5222
                else if (location.HasFlag(Location.Up))
5223
                    y = SPPIDLabelLocation.Y2;
5224
            }
5225
        }
5226

    
5227
        /// <summary>
5228
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5229
        /// 1. Angle Valve
5230
        /// 2. 3개로 이루어진 Symbol Group
5231
        /// </summary>
5232
        /// <returns></returns>
5233
        private List<Symbol> GetPrioritySymbol()
5234
        {
5235
            DataTable symbolTable = document.SymbolTable;
5236
            // List에 순서대로 쌓는다.
5237
            List<Symbol> symbols = new List<Symbol>();
5238

    
5239
            // Angle Valve 부터
5240
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5241
            {
5242
                if (!symbols.Contains(symbol))
5243
                {
5244
                    double originX = 0;
5245
                    double originY = 0;
5246

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

    
5251
                    SlopeType slopeType1 = SlopeType.None;
5252
                    SlopeType slopeType2 = SlopeType.None;
5253
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5254
                    {
5255
                        double connectorX = 0;
5256
                        double connectorY = 0;
5257
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5258
                        if (slopeType1 == SlopeType.None)
5259
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5260
                        else
5261
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5262
                    }
5263

    
5264
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5265
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5266
                        symbols.Add(symbol);
5267
                }
5268
            }
5269

    
5270
            List<Symbol> tempSymbols = new List<Symbol>();
5271
            // Conn 갯수 기준
5272
            foreach (var item in document.SYMBOLS)
5273
            {
5274
                if (!symbols.Contains(item))
5275
                    tempSymbols.Add(item);
5276
            }
5277
            tempSymbols.Sort(SortSymbolPriority);
5278
            symbols.AddRange(tempSymbols);
5279

    
5280
            return symbols;
5281
        }
5282

    
5283
        private void SetPriorityLine(List<Line> lines)
5284
        {
5285
            lines.Sort(SortLinePriority);
5286

    
5287
            int SortLinePriority(Line a, Line b)
5288
            {
5289
                // Branch 없는것부터
5290
                int branchRetval = CompareBranchLine(a, b);
5291
                if (branchRetval != 0)
5292
                {
5293
                    return branchRetval;
5294
                }
5295
                else
5296
                {
5297
                    // Symbol 연결 갯수
5298
                    int connSymbolRetval = CompareConnSymbol(a, b);
5299
                    if (connSymbolRetval != 0)
5300
                    {
5301
                        return connSymbolRetval;
5302
                    }
5303
                    else
5304
                    {
5305
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5306
                        int connItemRetval = CompareConnItem(a, b);
5307
                        if (connItemRetval != 0)
5308
                        {
5309
                            return connItemRetval;
5310
                        }
5311
                        else
5312
                        {
5313
                            // ConnectedItem이 없는것
5314
                            int noneConnRetval = CompareNoneConn(a, b);
5315
                            if (noneConnRetval != 0)
5316
                            {
5317
                                return noneConnRetval;
5318
                            }
5319
                            else
5320
                            {
5321

    
5322
                            }
5323
                        }
5324
                    }
5325
                }
5326

    
5327
                return 0;
5328
            }
5329

    
5330
            int CompareNotSegmentLine(Line a, Line b)
5331
            {
5332
                List<Connector> connectorsA = a.CONNECTORS
5333
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5334
                    .ToList();
5335

    
5336
                List<Connector> connectorsB = b.CONNECTORS
5337
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5338
                    .ToList();
5339

    
5340
                // 오름차순
5341
                return connectorsB.Count.CompareTo(connectorsA.Count);
5342
            }
5343

    
5344
            int CompareConnSymbol(Line a, Line b)
5345
            {
5346
                List<Connector> connectorsA = a.CONNECTORS
5347
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5348
                    .ToList();
5349

    
5350
                List<Connector> connectorsB = b.CONNECTORS
5351
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5352
                    .ToList();
5353

    
5354
                // 오름차순
5355
                return connectorsB.Count.CompareTo(connectorsA.Count);
5356
            }
5357

    
5358
            int CompareConnItem(Line a, Line b)
5359
            {
5360
                List<Connector> connectorsA = a.CONNECTORS
5361
                    .Where(conn => conn.ConnectedObject != null && 
5362
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5363
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5364
                    .ToList();
5365

    
5366
                List<Connector> connectorsB = b.CONNECTORS
5367
                    .Where(conn => conn.ConnectedObject != null &&
5368
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5369
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5370
                    .ToList();
5371

    
5372
                // 오름차순
5373
                return connectorsB.Count.CompareTo(connectorsA.Count);
5374
            }
5375

    
5376
            int CompareBranchLine(Line a, Line b)
5377
            {
5378
                List<Connector> connectorsA = a.CONNECTORS
5379
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5380
                    .ToList();
5381
                List<Connector> connectorsB = b.CONNECTORS
5382
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5383
                    .ToList();
5384

    
5385
                // 내림차순
5386
                return connectorsA.Count.CompareTo(connectorsB.Count);
5387
            }
5388

    
5389
            int CompareNoneConn(Line a, Line b)
5390
            {
5391
                List<Connector> connectorsA = a.CONNECTORS
5392
                    .Where(conn => conn.ConnectedObject == null)
5393
                    .ToList();
5394

    
5395
                List<Connector> connectorsB = b.CONNECTORS
5396
                    .Where(conn => conn.ConnectedObject == null)
5397
                    .ToList();
5398

    
5399
                // 오름차순
5400
                return connectorsB.Count.CompareTo(connectorsA.Count);
5401
            }
5402
        }
5403

    
5404
        private void SortText(List<Text> texts)
5405
        {
5406
            texts.Sort(Sort);
5407

    
5408
            int Sort(Text a, Text b)
5409
            {
5410
                int yRetval = CompareY(a, b);
5411
                if (yRetval != 0)
5412
                {
5413
                    return yRetval;
5414
                }
5415
                else
5416
                {
5417
                    return CompareX(a, b);
5418
                }
5419
            }
5420

    
5421
            int CompareY(Text a, Text b)
5422
            {
5423
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5424
            }
5425

    
5426
            int CompareX(Text a, Text b)
5427
            {
5428
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5429
            }
5430
        }
5431
        private void SortNote(List<Note> notes)
5432
        {
5433
            notes.Sort(Sort);
5434

    
5435
            int Sort(Note a, Note b)
5436
            {
5437
                int yRetval = CompareY(a, b);
5438
                if (yRetval != 0)
5439
                {
5440
                    return yRetval;
5441
                }
5442
                else
5443
                {
5444
                    return CompareX(a, b);
5445
                }
5446
            }
5447

    
5448
            int CompareY(Note a, Note b)
5449
            {
5450
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5451
            }
5452

    
5453
            int CompareX(Note a, Note b)
5454
            {
5455
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5456
            }
5457
        }
5458

    
5459
        private void SortBranchLines()
5460
        {
5461
            BranchLines.Sort(SortBranchLine);
5462
            int SortBranchLine(Line a, Line b)
5463
            {
5464
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5465
                 x.ConnectedObject.GetType() == typeof(Line) &&
5466
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
5467
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5468

    
5469
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5470
                 x.ConnectedObject.GetType() == typeof(Line) &&
5471
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
5472
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5473

    
5474
                // 내림차순
5475
                return countA.CompareTo(countB);
5476
            }
5477
        }
5478

    
5479
        private static int SortSymbolPriority(Symbol a, Symbol b)
5480
        {
5481
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5482
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5483
            int retval = countB.CompareTo(countA);
5484
            if (retval != 0)
5485
                return retval;
5486
            else
5487
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
5488
        }
5489

    
5490
        private string GetSPPIDFileName(LMModelItem modelItem)
5491
        {
5492
            string symbolPath = null;
5493
            foreach (LMRepresentation rep in modelItem.Representations)
5494
            {
5495
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5496
                {
5497
                    symbolPath = rep.get_FileName();
5498
                    break;
5499
                }
5500
            }
5501
            return symbolPath;
5502
        }
5503

    
5504
        private string GetSPPIDFileName(string modelItemId)
5505
        {
5506
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5507
            string symbolPath = null;
5508
            foreach (LMRepresentation rep in modelItem.Representations)
5509
            {
5510
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5511
                {
5512
                    symbolPath = rep.get_FileName();
5513
                    break;
5514
                }
5515
            }
5516
            ReleaseCOMObjects(modelItem);
5517
            return symbolPath;
5518
        }
5519

    
5520
        /// <summary>
5521
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
5522
        /// </summary>
5523
        /// <param name="graphicOID"></param>
5524
        /// <param name="milliseconds"></param>
5525
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
5526
        {
5527
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
5528
            {
5529
                double minX = 0;
5530
                double minY = 0;
5531
                double maxX = 0;
5532
                double maxY = 0;
5533
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
5534
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
5535

    
5536
                Thread.Sleep(milliseconds);
5537
            }
5538
        }
5539

    
5540
        /// <summary>
5541
        /// ComObject를 Release
5542
        /// </summary>
5543
        /// <param name="objVars"></param>
5544
        public void ReleaseCOMObjects(params object[] objVars)
5545
        {
5546
            if (objVars != null)
5547
            {
5548
                int intNewRefCount = 0;
5549
                foreach (object obj in objVars)
5550
                {
5551
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
5552
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
5553
                }
5554
            }
5555
        }
5556

    
5557
        /// IDisposable 구현
5558
        ~AutoModeling()
5559
        {
5560
            this.Dispose(false);
5561
        }
5562

    
5563
        private bool disposed;
5564
        public void Dispose()
5565
        {
5566
            this.Dispose(true);
5567
            GC.SuppressFinalize(this);
5568
        }
5569

    
5570
        protected virtual void Dispose(bool disposing)
5571
        {
5572
            if (this.disposed) return;
5573
            if (disposing)
5574
            {
5575
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
5576
            }
5577
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
5578
            this.disposed = true;
5579
        }
5580
    }
5581
}
클립보드 이미지 추가 (최대 크기: 500 MB)