프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ a560e00a

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

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

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

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

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

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

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

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

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

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

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

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

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

    
637
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
638

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

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

    
656
                SetFlowDirectionByLine(modelId);
657

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

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

    
673
                SetFlowDirectionByLine(modelId);
674

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1090
            LMSymbol _LMSymbol = null;
1091

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

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

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

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

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

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

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

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

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

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

    
1156

    
1157
                }
1158

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

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

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

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

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

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

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

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

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

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

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

    
1300
            return info;
1301
        }
1302

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

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

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

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

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

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

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

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

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

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

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

    
1407
            ReleaseCOMObjects(_TargetItem);
1408
        }
1409

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

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

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

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

    
1454
            ReleaseCOMObjects(_TargetItem);
1455
        }
1456

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

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

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

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

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

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

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

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

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

    
1607
                ReleaseCOMObjects(_TargetItem);
1608
            }
1609

    
1610
            range = tempRange;
1611
        }
1612

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

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

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

    
1647
                ReleaseCOMObjects(_ChildSymbol);
1648
            }
1649
        }
1650

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

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

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

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

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

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

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

    
1744
                                        if (result)
1745
                                            break;
1746
                                    }
1747

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

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

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

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

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

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

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

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

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

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

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

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

    
1859
            ReleaseCOMObjects(_LMSymbol);
1860
        }
1861

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

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

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

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

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

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

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

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

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

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

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

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

    
2061

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

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

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

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

    
2155
                            placeRunInputs.AddPoint(x, y);
2156

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

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

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

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

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

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

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

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

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

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

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

    
2255
                ReleaseCOMObjects(modelItem);
2256
            }
2257
        }
2258

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2604
            ReleaseCOMObjects(modelItem);
2605
        }
2606

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

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

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

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

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

    
2670
                    break;
2671
                }
2672
            }
2673

    
2674
            return _LMSymbol;
2675
        }
2676

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

    
2693
            return null;
2694
        }
2695

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

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

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

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

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

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

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

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

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

    
2811
            return newConnector;
2812
        }
2813

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2992
            }
2993

    
2994
            return targetConnector;
2995
        }
2996

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

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

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

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

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

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

    
3104
            return result;
3105
        }
3106

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

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

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

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

    
3153
                    ReleaseCOMObjects(_LMConnector);
3154
                }
3155
            }
3156

    
3157

    
3158
            return result;
3159
        }
3160

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3321

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

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

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

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

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

    
3354

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

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

    
3381

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

    
3390
                return findResult;
3391
            }
3392
        }
3393

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

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

    
3434
                ReleaseCOMObjects(modelItem);
3435
            }
3436

    
3437
            return connectorVertices;
3438
        }
3439

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

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

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

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

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

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

    
3525
            return targetConnector;
3526
        }
3527

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

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

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

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

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

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

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

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

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

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

    
3622
                GridSetting gridSetting = GridSetting.GetInstance();
3623

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

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

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

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

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

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

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

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

    
3786
            return targetConnector;
3787
        }
3788

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

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

    
3803
                ReleaseCOMObjects(modelItem);
3804
            }
3805

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

    
3812
            return result;
3813
        }
3814

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

    
3830
            return result;
3831
        }
3832

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

    
3847
            return result;
3848
        }
3849

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4040

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

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

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

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

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

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

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

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

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

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

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

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

    
4251
                    ReleaseCOMObjects(targetLMConnector);
4252
                }
4253
            }
4254

    
4255

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4607

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4840
                            ReleaseCOMObjects(labelPersist);
4841
                        }
4842

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

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

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

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

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

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

    
4944
                endTexts.AddRange(texts);
4945

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

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

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

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

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

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

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

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

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

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

    
5053

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

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

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

    
5108

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

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

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

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

    
5148
            endList.Add(note);
5149
        }
5150

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

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

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

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

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

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

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

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

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

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

    
5279
            return symbols;
5280
        }
5281

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

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

    
5321
                            }
5322
                        }
5323
                    }
5324
                }
5325

    
5326
                return 0;
5327
            }
5328

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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