프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ bccacd6c

이력 | 보기 | 이력해설 | 다운로드 (191 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, 18);
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
                    RunClearValueInconsistancy();
102
                    // EndBreak Modeling
103
                    RunEndBreakModeling();
104
                    // SpecBreak Modeling
105
                    RunSpecBreakModeling();
106
                    // Join SameConnector
107
                    RunJoinRunForSameConnector();
108
                    // Check FlowDirection
109
                    RunFlowDirection();
110
                    // Join Run
111
                    RunJoinRun();
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
                    // Label Symbol Modeling
125
                    RunLabelSymbolModeling();
126

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

    
152
                Log.Write("End Modeling");
153
                radApp.ActiveWindow.Fit();
154

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

    
172
                ReleaseCOMObjects(dataSource);
173
                dataSource = null;
174
                ReleaseCOMObjects(_placement);
175
                _placement = null;
176

    
177
                Thread.Sleep(1000);
178
            }
179
        }
180

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

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

    
229
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
230
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
231

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

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

    
271
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
272
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
273
            foreach (var item in stepLast_Line)
274
            {
275
                try
276
                {
277
                    NewLineModeling(item);
278
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
279
                }
280
                catch (Exception ex)
281
                {
282
                    Log.Write("Error in NewLineModeling");
283
                    Log.Write("UID : " + item.UID);
284
                    Log.Write(ex.Message);
285
                    Log.Write(ex.StackTrace);
286
                }
287
            }
288
        }
289
        private void RunClearValueInconsistancy()
290
        {
291
            int count = 1;
292
            bool loop = true;
293
            while (loop)
294
            {
295
                loop = false;
296
                LMAFilter filter = new LMAFilter();
297
                LMACriterion criterion = new LMACriterion();
298
                filter.ItemType = "Relationship";
299
                criterion.SourceAttributeName = "SP_DRAWINGID";
300
                criterion.Operator = "=";
301
                criterion.set_ValueAttribute(drawingID);
302
                filter.get_Criteria().Add(criterion);
303

    
304
                LMRelationships relationships = new LMRelationships();
305
                relationships.Collect(dataSource, Filter: filter);
306

    
307
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
308
                if (count > 1)
309
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
310
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
311
                foreach (LMRelationship relationship in relationships)
312
                {
313
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
314
                    {
315
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
316
                        {
317
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
318
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
319
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
320
                            if (modelItem1 != null)
321
                            {
322
                                string attrName = array[0];
323
                                if (attrName.Contains("PipingPoint"))
324
                                {
325
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
326
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
327
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
328
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
329
                                    {
330
                                        loop = true;
331
                                        attribute1.set_Value(DBNull.Value);
332
                                    }
333
                                    attribute1 = null;
334
                                }
335
                                else
336
                                {
337
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
338
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
339
                                    {
340
                                        loop = true;
341
                                        attribute1.set_Value(DBNull.Value);
342
                                    }
343
                                    attribute1 = null;
344
                                }
345
                                modelItem1.Commit();
346
                            }
347
                            if (modelItem2 != null)
348
                            {
349
                                string attrName = array[1];
350
                                if (attrName.Contains("PipingPoint"))
351
                                {
352
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
353
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
354
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
355
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
356
                                    {
357
                                        attribute2.set_Value(DBNull.Value);
358
                                        loop = true;
359
                                    }
360
                                    attribute2 = null;
361
                                }
362
                                else
363
                                {
364
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
365
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
366
                                    {
367
                                        attribute2.set_Value(DBNull.Value);
368
                                        loop = true;
369
                                    }
370
                                    attribute2 = null;
371
                                }
372
                                modelItem2.Commit();
373
                            }
374
                            ReleaseCOMObjects(modelItem1);
375
                            modelItem1 = null;
376
                            ReleaseCOMObjects(modelItem2);
377
                            modelItem2 = null;
378
                            inconsistency.Commit();
379
                        }
380
                        ReleaseCOMObjects(inconsistency);
381
                    }
382
                    relationship.Commit();
383
                    ReleaseCOMObjects(relationship);
384
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
385
                }
386
                ReleaseCOMObjects(filter);
387
                filter = null;
388
                ReleaseCOMObjects(criterion);
389
                criterion = null;
390
                ReleaseCOMObjects(relationships);
391
                relationships = null;
392
                count++;
393
            }
394
        }
395
        private void RunEndBreakModeling()
396
        {
397
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
398
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
399
            foreach (var item in document.EndBreaks)
400
                try
401
                {
402
                    EndBreakModeling(item);
403
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
404
                }
405
                catch (Exception ex)
406
                {
407
                    Log.Write("Error in EndBreakModeling");
408
                    Log.Write("UID : " + item.UID);
409
                    Log.Write(ex.Message);
410
                    Log.Write(ex.StackTrace);
411
                }
412
        }
413
        private void RunSpecBreakModeling()
414
        {
415
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
416
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
417
            foreach (var item in document.SpecBreaks)
418
                try
419
                {
420
                    SpecBreakModeling(item);
421
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
422
                }
423
                catch (Exception ex)
424
                {
425
                    Log.Write("Error in SpecBreakModeling");
426
                    Log.Write("UID : " + item.UID);
427
                    Log.Write(ex.Message);
428
                    Log.Write(ex.StackTrace);
429
                }
430
        }
431
        private void RunJoinRunForSameConnector()
432
        {
433
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
434
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
435
            foreach (var line in document.LINES)
436
            {
437
                if (!SPPIDUtil.IsSegmentLine(document, line))
438
                {
439
                    foreach (var connector in line.CONNECTORS)
440
                    {
441
                        if (connector.ConnectedObject != null &&
442
                            connector.ConnectedObject.GetType() == typeof(Line) &&
443
                            !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
444
                        {
445
                            Line connLine = connector.ConnectedObject as Line;
446
                            if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(connLine.SPPID.ModelItemId))
447
                            {
448
                                string survivorId = string.Empty;
449
                                JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
450
                            }
451
                                
452
                        }
453
                    }
454
                }
455
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
456
            }
457
        }
458
        private void RunJoinRun()
459
        {
460
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
461
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
462
            List<string> endModelID = new List<string>();
463
            foreach (var line in document.LINES)
464
            {
465
                if (!endModelID.Contains(line.SPPID.ModelItemId))
466
                {
467
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
468
                    {
469
                        string survivorId = string.Empty;
470
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
471
                        if (string.IsNullOrEmpty(survivorId))
472
                        {
473
                            endModelID.Add(line.SPPID.ModelItemId);
474
                        }
475
                    }
476
                }
477
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
478
            }
479
        }
480
        private void RunLineNumberModeling()
481
        {
482
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
483
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
484
            foreach (var item in document.LINENUMBERS)
485
            {
486
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
487
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
488
                {
489
                    ReleaseCOMObjects(label);
490
                    item.SPPID.RepresentationId = null;
491
                    LineNumberModeling(item);
492
                }
493
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
494
            }
495
        }
496
        private void RunFlowDirection()
497
        {
498
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, 
499
                document.LINES.Count + ZeroLengthModelItemID.Count + ZeroLengthModelItemIDReverse.Count + ZeroLengthSymbolToSymbolModelItemID.Count);
500
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Check Flow Direction");
501
            foreach (var line in document.LINES)
502
            {
503
                if (!string.IsNullOrEmpty(line.SPPID.ModelItemId))
504
                {
505
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
506
                    if (modelItem != null && modelItem.get_ItemStatus() == "Active")
507
                    {
508
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
509
                        if (attribute != null)
510
                        {
511
                            attribute.set_Value("End 1 is upstream (Inlet)");
512
                            modelItem.Commit();
513
                        }
514

    
515
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
516

    
517
                        ReleaseCOMObjects(modelItem);
518
                    }
519
                }
520

    
521
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
522
            }
523
            foreach (var modelId in ZeroLengthModelItemID)
524
            {
525
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
526
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
527
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
528
                {
529
                    attribute.set_Value("End 1 is upstream (Inlet)");
530
                    zeroLengthModelItem.Commit();
531
                }
532

    
533
                SetFlowDirectionByLine(modelId);
534

    
535
                ReleaseCOMObjects(zeroLengthModelItem);
536
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
537
            }
538
            foreach (var modelId in ZeroLengthModelItemIDReverse)
539
            {
540
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
541
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
542
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
543
                {
544
                    attribute.set_Value("End 1 is downstream (Outlet)");
545
                    zeroLengthModelItem.Commit();
546
                }
547

    
548
                SetFlowDirectionByLine(modelId);
549

    
550
                ReleaseCOMObjects(zeroLengthModelItem);
551
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
552
            }
553
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
554
            {
555
                SetFlowDirectionByLine(modelId);
556
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
557
            }
558

    
559
            void SetFlowDirectionByLine(string lineModelItemID)
560
            {
561
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
562
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
563
                {
564
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
565
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
566
                    {
567
                        string sFlowDirection = attribute.get_Value().ToString();
568
                        foreach (LMRepresentation rep in modelItem.Representations)
569
                        {
570
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
571
                            {
572
                                LMConnector connector = dataSource.GetConnector(rep.Id);
573

    
574
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
575
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
576
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
577
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
578

    
579
                                ReleaseCOMObjects(connector);
580
                            }
581
                        }
582
                    }
583
                    ReleaseCOMObjects(modelItem);
584
                }
585

    
586
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
587
                {
588
                    // Item2가 Symbol
589
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
590
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
591
                    {
592
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
593
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
594
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
595

    
596
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
597

    
598
                        symbolModelItem.Commit();
599
                        ReleaseCOMObjects(symbolModelItem);
600
                    }
601
                    // Item1이 Symbol
602
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
603
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
604
                    {
605
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
606
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
607
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
608

    
609
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
610

    
611
                        symbolModelItem.Commit();
612
                        ReleaseCOMObjects(symbolModelItem);
613
                    }
614
                }
615

    
616
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
617
                {
618
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
619
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
620
                    if (attribute != null)
621
                    {
622
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
623
                            attribute.set_Value("End 1 is downstream (Outlet)");
624
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
625
                            attribute.set_Value("End 1 is upstream (Inlet)");
626
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
627
                            attribute.set_Value("End 1 is upstream (Inlet)");
628
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
629
                            attribute.set_Value("End 1 is downstream (Outlet)");
630
                    }
631
                }
632
            }
633
        }
634
        private void RunNoteModeling()
635
        {
636
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
637
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
638
            foreach (var item in document.NOTES)
639
                try
640
                {
641
                    NoteModeling(item);
642
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
643
                }
644
                catch (Exception ex)
645
                {
646
                    Log.Write("Error in NoteModeling");
647
                    Log.Write("UID : " + item.UID);
648
                    Log.Write(ex.Message);
649
                    Log.Write(ex.StackTrace);
650
                }
651
        }
652
        private void RunTextModeling()
653
        {
654
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
655
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
656
            foreach (var item in document.TEXTINFOS)
657
                try
658
                {
659
                    TextModeling(item);
660
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
661
                }
662
                catch (Exception ex)
663
                {
664
                    Log.Write("Error in TextModeling");
665
                    Log.Write("UID : " + item.UID);
666
                    Log.Write(ex.Message);
667
                    Log.Write(ex.StackTrace);
668
                }
669
        }
670
        private void RunInputLineNumberAttribute()
671
        {
672
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
673
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
674
            List<string> endLine = new List<string>();
675
            foreach (var item in document.LINENUMBERS)
676
                try
677
                {
678
                    InputLineNumberAttribute(item, endLine);
679
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
680
                }
681
                catch (Exception ex)
682
                {
683
                    Log.Write("Error in InputLineNumberAttribute");
684
                    Log.Write("UID : " + item.UID);
685
                    Log.Write(ex.Message);
686
                    Log.Write(ex.StackTrace);
687
                }
688
        }
689
        private void RunInputSymbolAttribute()
690
        {
691
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
692
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
693
            foreach (var item in document.SYMBOLS)
694
                try
695
                {
696
                    InputSymbolAttribute(item, item.ATTRIBUTES);
697
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
698
                }
699
                catch (Exception ex)
700
                {
701
                    Log.Write("Error in InputSymbolAttribute");
702
                    Log.Write("UID : " + item.UID);
703
                    Log.Write(ex.Message);
704
                    Log.Write(ex.StackTrace);
705
                }
706
        }
707
        private void RunInputSpecBreakAttribute()
708
        {
709
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
710
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
711
            foreach (var item in document.SpecBreaks)
712
                try
713
                {
714
                    InputSpecBreakAttribute(item);
715
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
716
                }
717
                catch (Exception ex)
718
                {
719
                    Log.Write("Error in InputSpecBreakAttribute");
720
                    Log.Write("UID : " + item.UID);
721
                    Log.Write(ex.Message);
722
                    Log.Write(ex.StackTrace);
723
                }
724
        }
725
        private void RunLabelSymbolModeling()
726
        {
727
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
728
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
729
            foreach (var item in document.SYMBOLS)
730
                try
731
                {
732
                    LabelSymbolModeling(item);
733
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
734
                }
735
                catch (Exception ex)
736
                {
737
                    Log.Write("Error in LabelSymbolModeling");
738
                    Log.Write("UID : " + item.UID);
739
                    Log.Write(ex.Message);
740
                    Log.Write(ex.StackTrace);
741
                }
742
        }
743
        
744
        /// <summary>
745
        /// 도면 생성 메서드
746
        /// </summary>
747
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
748
        {
749
            Log.Write("------------------ Start create document ------------------");
750
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
751
            Log.Write("Drawing name : " + drawingName);
752
            Log.Write("Drawing number : " + drawingNumber);
753
            Thread.Sleep(1000);
754
            radApp.RunCommand(Ingr.RAD2D.CommandConstants.igcmdWindowRefresh);
755
            Thread.Sleep(1000);
756
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
757
            if (newDrawing != null)
758
            {
759
                document.SPPID_DrawingNumber = drawingNumber;
760
                document.SPPID_DrawingName = drawingName;
761
                Thread.Sleep(1000);
762
                radApp.ActiveWindow.Fit();
763
                Thread.Sleep(1000);
764
                radApp.ActiveWindow.Zoom = 2000;
765
                Thread.Sleep(2000);
766

    
767
                //current LMDrawing 가져오기
768
                LMAFilter filter = new LMAFilter();
769
                LMACriterion criterion = new LMACriterion();
770
                filter.ItemType = "Drawing";
771
                criterion.SourceAttributeName = "Name";
772
                criterion.Operator = "=";
773
                criterion.set_ValueAttribute(drawingName);
774
                filter.get_Criteria().Add(criterion);
775

    
776
                LMDrawings drawings = new LMDrawings();
777
                drawings.Collect(dataSource, Filter: filter);
778

    
779
                drawingID = ((dynamic)drawings).Nth(1).Id;
780
                ReleaseCOMObjects(filter);
781
                ReleaseCOMObjects(criterion);
782
                ReleaseCOMObjects(drawings);
783
                filter = null;
784
                criterion = null;
785
                drawings = null;
786
            }
787
            else
788
                Log.Write("Fail Create Drawing");
789

    
790
            if (newDrawing != null)
791
                return true;
792
            else
793
                return false;
794
        }
795

    
796
        /// <summary>
797
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
798
        /// </summary>
799
        /// <param name="drawingName"></param>
800
        /// <param name="drawingNumber"></param>
801
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
802
        {
803
            LMDrawings drawings = new LMDrawings();
804
            drawings.Collect(dataSource);
805

    
806
            List<string> drawingNameList = new List<string>();
807
            List<string> drawingNumberList = new List<string>();
808

    
809
            foreach (LMDrawing item in drawings)
810
            {
811
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
812
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
813
            }
814

    
815
            int nameLength = drawingName.Length;
816
            while (drawingNameList.Contains(drawingName))
817
            {
818
                if (nameLength == drawingName.Length)
819
                    drawingName += "-1";
820
                else
821
                {
822
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
823
                    drawingName = drawingName.Substring(0, nameLength + 1);
824
                    drawingName += ++index;
825
                }
826
            }
827

    
828
            int numberLength = drawingNumber.Length;
829
            while (drawingNameList.Contains(drawingNumber))
830
            {
831
                if (numberLength == drawingNumber.Length)
832
                    drawingNumber += "-1";
833
                else
834
                {
835
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
836
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
837
                    drawingNumber += ++index;
838
                }
839
            }
840
            ReleaseCOMObjects(dataSource);
841
            dataSource = null;
842
            ReleaseCOMObjects(drawings);
843
            drawings = null;
844
        }
845

    
846
        /// <summary>
847
        /// 도면 크기 구하는 메서드
848
        /// </summary>
849
        /// <returns></returns>
850
        private bool DocumentCoordinateCorrection()
851
        {
852
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
853
            {
854
                Log.Write("Setting Drawing X, Drawing Y");
855
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
856
                Log.Write("Start coordinate correction");
857
                document.CoordinateCorrection();
858
                return true;
859
            }
860
            else
861
            {
862
                Log.Write("Need Drawing X, Y");
863
                return false;
864
            }
865
        }
866

    
867
        /// <summary>
868
        /// 심볼을 실제로 Modeling 메서드
869
        /// </summary>
870
        /// <param name="symbol">생성할 심볼</param>
871
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
872
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
873
        {
874
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
875
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
876
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
877
                return;
878
            // 이미 모델링 됐을 경우
879
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
880
                return;
881

    
882
            LMSymbol _LMSymbol = null;
883

    
884
            string mappingPath = symbol.SPPID.MAPPINGNAME;
885
            double x = symbol.SPPID.ORIGINAL_X;
886
            double y = symbol.SPPID.ORIGINAL_Y;
887
            int mirror = 0;
888
            double angle = symbol.ANGLE;
889

    
890
            // OPC 일경우 180도 일때 Mirror
891
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
892
                mirror = 1;
893

    
894
            // Mirror 계산
895
            if (symbol.FLIP == 1)
896
            {
897
                mirror = 1;
898
                angle += Math.PI;
899
            }
900

    
901
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
902
            {
903
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
904
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
905
                if (connector != null)
906
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
907

    
908
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
909

    
910
                if (_LMSymbol != null && _TargetItem != null)
911
                {
912
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
913

    
914
                    if (SPPIDUtil.IsSegmentLine(document, symbol, targetSymbol))
915
                    {
916
                        LMConnector reModelingConnector = FindBreakLineTarget(symbol, targetSymbol);
917
                        if (reModelingConnector != null)
918
                            ReModelingLMConnector(reModelingConnector);
919
                    }
920
                }
921

    
922
                ReleaseCOMObjects(_TargetItem);
923
            }
924
            else
925
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
926

    
927
            if (_LMSymbol != null)
928
            {
929
                _LMSymbol.Commit();
930

    
931
                // ConnCheck
932
                List<string> ids = new List<string>();
933
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
934
                {
935
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
936
                        ids.Add(item.Id);
937
                    ReleaseCOMObjects(item);
938
                }
939
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
940
                {
941
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
942
                        ids.Add(item.Id);
943
                    ReleaseCOMObjects(item);
944
                }
945

    
946
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
947
                if (targetSymbol == null && ids.Count != createdSymbolCount)
948
                {
949
                    double currentX = _LMSymbol.get_XCoordinate();
950
                    double currentY = _LMSymbol.get_YCoordinate();
951

    
952

    
953
                }
954

    
955
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
956
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
957
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
958

    
959
                foreach (var item in symbol.ChildSymbols)
960
                    CreateChildSymbol(item, _LMSymbol, symbol);
961

    
962
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
963
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
964

    
965
                double[] range = null;
966
                GetSPPIDSymbolRange(symbol, ref range);
967
                symbol.SPPID.SPPID_Min_X = range[0];
968
                symbol.SPPID.SPPID_Min_Y = range[1];
969
                symbol.SPPID.SPPID_Max_X = range[2];
970
                symbol.SPPID.SPPID_Max_Y = range[3];
971

    
972
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
973
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
974
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
975
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
976

    
977
                ReleaseCOMObjects(_LMSymbol);
978
            }
979
        }
980

    
981
        private void RemoveSymbol(Symbol symbol)
982
        {
983
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
984
            {
985
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
986
                if (_LMSymbol != null)
987
                {
988
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
989
                    ReleaseCOMObjects(_LMSymbol);
990
                }
991
            }
992

    
993
            symbol.SPPID.RepresentationId = string.Empty;
994
            symbol.SPPID.ModelItemID = string.Empty;
995
            symbol.SPPID.SPPID_X = double.NaN;
996
            symbol.SPPID.SPPID_Y = double.NaN;
997
            symbol.SPPID.SPPID_Min_X = double.NaN;
998
            symbol.SPPID.SPPID_Min_Y = double.NaN;
999
            symbol.SPPID.SPPID_Max_X = double.NaN;
1000
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1001
        }
1002

    
1003
        private void RemoveSymbol(List<Symbol> symbols)
1004
        {
1005
            foreach (var symbol in symbols)
1006
            {
1007
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1008
                {
1009
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1010
                    if (_LMSymbol != null)
1011
                    {
1012
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1013
                        ReleaseCOMObjects(_LMSymbol);
1014
                    }
1015
                }
1016

    
1017
                symbol.SPPID.RepresentationId = string.Empty;
1018
                symbol.SPPID.ModelItemID = string.Empty;
1019
                symbol.SPPID.SPPID_X = double.NaN;
1020
                symbol.SPPID.SPPID_Y = double.NaN;
1021
                symbol.SPPID.SPPID_Min_X = double.NaN;
1022
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1023
                symbol.SPPID.SPPID_Max_X = double.NaN;
1024
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1025
            }
1026
        }
1027

    
1028
        /// <summary>
1029
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1030
        /// </summary>
1031
        /// <param name="targetConnector"></param>
1032
        /// <param name="targetSymbol"></param>
1033
        /// <param name="x"></param>
1034
        /// <param name="y"></param>
1035
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1036
        {
1037
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1038

    
1039
            double[] range = null;
1040
            List<double[]> points = new List<double[]>();
1041
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1042
            double x1 = range[0];
1043
            double y1 = range[1];
1044
            double x2 = range[2];
1045
            double y2 = range[3];
1046

    
1047
            // Origin 기준 Connector의 위치차이
1048
            double sceneX = 0;
1049
            double sceneY = 0;
1050
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1051
            double originX = 0;
1052
            double originY = 0;
1053
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1054
            double gapX = originX - sceneX;
1055
            double gapY = originY - sceneY;
1056

    
1057
            // SPPID Symbol과 ID2 심볼의 크기 차이
1058
            double sizeWidth = 0;
1059
            double sizeHeight = 0;
1060
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1061
            if (sizeWidth == 0 || sizeHeight == 0)
1062
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1063

    
1064
            double percentX = (x2 - x1) / sizeWidth;
1065
            double percentY = (y2 - y1) / sizeHeight;
1066

    
1067
            double SPPIDgapX = gapX * percentX;
1068
            double SPPIDgapY = gapY * percentY;
1069

    
1070
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1071
            double distance = double.MaxValue;
1072
            double[] resultPoint;
1073
            foreach (var point in points)
1074
            {
1075
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1076
                if (distance > result)
1077
                {
1078
                    distance = result;
1079
                    resultPoint = point;
1080
                    x = point[0];
1081
                    y = point[1];
1082
                }
1083
            }
1084

    
1085
            ReleaseCOMObjects(_TargetItem);
1086
        }
1087

    
1088
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1089
        {
1090
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1091
            if (index == 0)
1092
            {
1093
                x = targetLine.SPPID.START_X;
1094
                y = targetLine.SPPID.START_Y;
1095
            }
1096
            else
1097
            {
1098
                x = targetLine.SPPID.END_X;
1099
                y = targetLine.SPPID.END_Y;
1100
            }
1101
        }
1102

    
1103
        /// <summary>
1104
        /// SPPID Symbol의 Range를 구한다.
1105
        /// </summary>
1106
        /// <param name="symbol"></param>
1107
        /// <param name="range"></param>
1108
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1109
        {
1110
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1111
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1112
            double x1 = 0;
1113
            double y1 = 0;
1114
            double x2 = 0;
1115
            double y2 = 0;
1116
            symbol2d.Range(out x1, out y1, out x2, out y2);
1117
            range = new double[] { x1, y1, x2, y2 };
1118

    
1119
            for (int i = 1; i < int.MaxValue; i++)
1120
            {
1121
                double connX = 0;
1122
                double connY = 0;
1123
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1124
                    points.Add(new double[] { connX, connY });
1125
                else
1126
                    break;
1127
            }
1128

    
1129
            foreach (var childSymbol in symbol.ChildSymbols)
1130
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1131

    
1132
            ReleaseCOMObjects(_TargetItem);
1133
        }
1134

    
1135
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range)
1136
        {
1137
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1138
            if (_TargetItem != null)
1139
            {
1140
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1141
                double x1 = 0;
1142
                double y1 = 0;
1143
                double x2 = 0;
1144
                double y2 = 0;
1145
                symbol2d.Range(out x1, out y1, out x2, out y2);
1146
                range = new double[] { x1, y1, x2, y2 };
1147

    
1148
                foreach (var childSymbol in symbol.ChildSymbols)
1149
                    GetSPPIDChildSymbolRange(childSymbol, ref range);
1150

    
1151
                ReleaseCOMObjects(_TargetItem);
1152
            }
1153
        }
1154

    
1155
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1156
        {
1157
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1158
            foreach (var symbol in symbols)
1159
            {
1160
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1161
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1162
                double x1 = 0;
1163
                double y1 = 0;
1164
                double x2 = 0;
1165
                double y2 = 0;
1166
                symbol2d.Range(out x1, out y1, out x2, out y2);
1167

    
1168
                tempRange[0] = Math.Min(tempRange[0], x1);
1169
                tempRange[1] = Math.Min(tempRange[1], y1);
1170
                tempRange[2] = Math.Max(tempRange[2], x2);
1171
                tempRange[3] = Math.Max(tempRange[3], y2);
1172

    
1173
                foreach (var childSymbol in symbol.ChildSymbols)
1174
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1175

    
1176
                ReleaseCOMObjects(_TargetItem);
1177
            }
1178

    
1179
            range = tempRange;
1180
        }
1181

    
1182
        /// <summary>
1183
        /// Child Modeling 된 Symbol의 Range를 구한다.
1184
        /// </summary>
1185
        /// <param name="childSymbol"></param>
1186
        /// <param name="range"></param>
1187
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1188
        {
1189
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1190
            if (_ChildSymbol != null)
1191
            {
1192
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1193
                double x1 = 0;
1194
                double y1 = 0;
1195
                double x2 = 0;
1196
                double y2 = 0;
1197
                symbol2d.Range(out x1, out y1, out x2, out y2);
1198
                range[0] = Math.Min(range[0], x1);
1199
                range[1] = Math.Min(range[1], y1);
1200
                range[2] = Math.Max(range[2], x2);
1201
                range[3] = Math.Max(range[3], y2);
1202

    
1203
                for (int i = 1; i < int.MaxValue; i++)
1204
                {
1205
                    double connX = 0;
1206
                    double connY = 0;
1207
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1208
                        points.Add(new double[] { connX, connY });
1209
                    else
1210
                        break;
1211
                }
1212

    
1213
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1214
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1215

    
1216
                ReleaseCOMObjects(_ChildSymbol);
1217
            }
1218
        }
1219

    
1220
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1221
        {
1222
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1223
            if (_ChildSymbol != null)
1224
            {
1225
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1226
                double x1 = 0;
1227
                double y1 = 0;
1228
                double x2 = 0;
1229
                double y2 = 0;
1230
                symbol2d.Range(out x1, out y1, out x2, out y2);
1231
                range[0] = Math.Min(range[0], x1);
1232
                range[1] = Math.Min(range[1], y1);
1233
                range[2] = Math.Max(range[2], x2);
1234
                range[3] = Math.Max(range[3], y2);
1235

    
1236
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1237
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1238
                ReleaseCOMObjects(_ChildSymbol);
1239
            }
1240
        }
1241

    
1242
        /// <summary>
1243
        /// Label Symbol Modeling
1244
        /// </summary>
1245
        /// <param name="symbol"></param>
1246
        private void LabelSymbolModeling(Symbol symbol)
1247
        {
1248
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1249
            {
1250
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1251
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1252
                    return;
1253
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1254

    
1255
                string symbolUID = itemAttribute.VALUE;
1256
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1257
                if (targetItem != null &&
1258
                    (targetItem.GetType() == typeof(Symbol) ||
1259
                    targetItem.GetType() == typeof(Equipment)))
1260
                {
1261
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1262
                    string sRep = null;
1263
                    if (targetItem.GetType() == typeof(Symbol))
1264
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1265
                    else if (targetItem.GetType() == typeof(Equipment))
1266
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1267
                    if (!string.IsNullOrEmpty(sRep))
1268
                    {
1269
                        // LEADER Line 검사
1270
                        bool leaderLine = false;
1271
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1272
                        if (symbolMapping != null)
1273
                            leaderLine = symbolMapping.LEADERLINE;
1274

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

    
1279
                        //Leader 선 센터로
1280
                        if (_LMLabelPresist != null)
1281
                        {
1282
                            // Target Item에 Label의 Attribute Input
1283
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1284

    
1285
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1286
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1287
                            if (dependency != null)
1288
                            {
1289
                                bool result = false;
1290
                                foreach (var attributes in dependency.AttributeSets)
1291
                                {
1292
                                    foreach (var attribute in attributes)
1293
                                    {
1294
                                        string name = attribute.Name;
1295
                                        string value = attribute.GetValue().ToString();
1296
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1297
                                        {
1298
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1299
                                            {
1300
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1301
                                                {
1302
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1303
                                                    double prevX = _TargetItem.get_XCoordinate();
1304
                                                    double prevY = _TargetItem.get_YCoordinate();
1305
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1306
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1307
                                                    result = true;
1308
                                                    break;
1309
                                                }
1310
                                            }
1311
                                        }
1312

    
1313
                                        if (result)
1314
                                            break;
1315
                                    }
1316

    
1317
                                    if (result)
1318
                                        break;
1319
                                }
1320
                            }
1321

    
1322
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1323
                            _LMLabelPresist.Commit();
1324
                            ReleaseCOMObjects(_LMLabelPresist);
1325
                        }
1326

    
1327
                        ReleaseCOMObjects(_TargetItem);
1328
                    }
1329
                }
1330
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1331
                {
1332
                    Line targetLine = targetItem as Line;
1333
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1334
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1335
                    if (connectedLMConnector != null)
1336
                    {
1337
                        // LEADER Line 검사
1338
                        bool leaderLine = false;
1339
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1340
                        if (symbolMapping != null)
1341
                            leaderLine = symbolMapping.LEADERLINE;
1342

    
1343
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1344
                        if (_LMLabelPresist != null)
1345
                        {
1346
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1347
                            _LMLabelPresist.Commit();
1348
                            ReleaseCOMObjects(_LMLabelPresist);
1349
                        }
1350
                        ReleaseCOMObjects(connectedLMConnector);
1351
                    }
1352

    
1353
                    foreach (var item in connectorVertices)
1354
                        if (item.Key != null)
1355
                            ReleaseCOMObjects(item.Key);
1356
                }
1357
            }
1358
        }
1359

    
1360
        /// <summary>
1361
        /// Equipment를 실제로 Modeling 메서드
1362
        /// </summary>
1363
        /// <param name="equipment"></param>
1364
        private void EquipmentModeling(Equipment equipment)
1365
        {
1366
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1367
                return;
1368

    
1369
            LMSymbol _LMSymbol = null;
1370
            LMSymbol targetItem = null;
1371
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1372
            double x = equipment.SPPID.ORIGINAL_X;
1373
            double y = equipment.SPPID.ORIGINAL_Y;
1374
            int mirror = 0;
1375
            double angle = equipment.ANGLE;
1376

    
1377
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1378

    
1379
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1380
            if (connector != null)
1381
            {
1382
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1383
                if (connEquipment != null)
1384
                {
1385
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1386
                        EquipmentModeling(connEquipment);
1387

    
1388
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1389
                    {
1390
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1391
                        if (targetItem != null)
1392
                        {
1393
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1394
                        }
1395
                        else
1396
                        {
1397
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1398
                        }
1399
                    }
1400
                    else
1401
                    {
1402
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1403
                    }
1404
                }
1405
                else
1406
                {
1407
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1408
                }
1409
            }
1410
            else
1411
            {
1412
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1413
            }
1414

    
1415
            if (_LMSymbol != null)
1416
            {
1417
                _LMSymbol.Commit();
1418
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1419
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1420
                ReleaseCOMObjects(_LMSymbol);
1421
            }
1422

    
1423
            if (targetItem != null)
1424
            {
1425
                ReleaseCOMObjects(targetItem);
1426
            }
1427

    
1428
            ReleaseCOMObjects(_LMSymbol);
1429
        }
1430

    
1431
        /// <summary>
1432
        /// 첫 진입점
1433
        /// </summary>
1434
        /// <param name="symbol"></param>
1435
        private void SymbolModelingBySymbol(Symbol symbol)
1436
        {
1437
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1438
            List<object> endObjects = new List<object>();
1439
            endObjects.Add(symbol);
1440

    
1441
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1442
            foreach (var connector in symbol.CONNECTORS)
1443
            {
1444
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1445
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1446
                {
1447
                    endObjects.Add(connItem);
1448
                    if (connItem.GetType() == typeof(Symbol))
1449
                    {
1450
                        Symbol connSymbol = connItem as Symbol;
1451
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1452
                        {
1453
                            SymbolModeling(connSymbol, symbol);
1454
                        }
1455
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1456
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1457
                    }
1458
                    else if (connItem.GetType() == typeof(Line))
1459
                    {
1460
                        Line connLine = connItem as Line;
1461
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1462
                    }
1463
                }
1464
            }
1465
        }
1466

    
1467
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1468
        {
1469
            foreach (var connector in symbol.CONNECTORS)
1470
            {
1471
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1472
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1473
                {
1474
                    if (!endObjects.Contains(connItem))
1475
                    {
1476
                        endObjects.Add(connItem);
1477
                        if (connItem.GetType() == typeof(Symbol))
1478
                        {
1479
                            Symbol connSymbol = connItem as Symbol;
1480
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1481
                            {
1482
                                SymbolModeling(connSymbol, symbol);
1483
                            }
1484
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1485
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1486
                        }
1487
                        else if (connItem.GetType() == typeof(Line))
1488
                        {
1489
                            Line connLine = connItem as Line;
1490
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1491
                        }
1492
                    }
1493
                }
1494
            }
1495
        }
1496

    
1497
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1498
        {
1499
            foreach (var connector in line.CONNECTORS)
1500
            {
1501
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1502
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1503
                {
1504
                    if (!endObjects.Contains(connItem))
1505
                    {
1506
                        endObjects.Add(connItem);
1507
                        if (connItem.GetType() == typeof(Symbol))
1508
                        {
1509
                            Symbol connSymbol = connItem as Symbol;
1510
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1511
                            {
1512
                                List<Symbol> group = new List<Symbol>();
1513
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1514
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1515
                                List<Symbol> endModelingGroup = new List<Symbol>();
1516
                                if (priority != null)
1517
                                {
1518
                                    SymbolGroupModeling(priority, group);
1519

    
1520
                                    // Range 겹치는지 확인해야함
1521
                                    double[] prevRange = null;
1522
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1523
                                    double[] groupRange = null;
1524
                                    GetSPPIDSymbolRange(group, ref groupRange);
1525

    
1526
                                    double distanceX = 0;
1527
                                    double distanceY = 0;
1528
                                    bool overlapX = false;
1529
                                    bool overlapY = false;
1530
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1531
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1532
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1533
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1534
                                    {
1535
                                        RemoveSymbol(group);
1536
                                        foreach (var _temp in group)
1537
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1538

    
1539
                                        SymbolGroupModeling(priority, group);
1540
                                    }
1541
                                }
1542
                                else
1543
                                {
1544
                                    SymbolModeling(connSymbol, null);
1545
                                    // Range 겹치는지 확인해야함
1546
                                    double[] prevRange = null;
1547
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1548
                                    double[] connRange = null;
1549
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1550

    
1551
                                    double distanceX = 0;
1552
                                    double distanceY = 0;
1553
                                    bool overlapX = false;
1554
                                    bool overlapY = false;
1555
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1556
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1557
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1558
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1559
                                    {
1560
                                        RemoveSymbol(connSymbol);
1561
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1562

    
1563
                                        SymbolModeling(connSymbol, null);
1564
                                    }
1565
                                }
1566
                            }
1567
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1568
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1569
                        }
1570
                        else if (connItem.GetType() == typeof(Line))
1571
                        {
1572
                            Line connLine = connItem as Line;
1573
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1574
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1575
                        }
1576
                    }
1577
                }
1578
            }
1579
        }
1580

    
1581
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1582
        {
1583
            List<Symbol> endModelingGroup = new List<Symbol>();
1584
            SymbolModeling(firstSymbol, null);
1585
            endModelingGroup.Add(firstSymbol);
1586
            while (endModelingGroup.Count != group.Count)
1587
            {
1588
                foreach (var _symbol in group)
1589
                {
1590
                    if (!endModelingGroup.Contains(_symbol))
1591
                    {
1592
                        foreach (var _connector in _symbol.CONNECTORS)
1593
                        {
1594
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
1595
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
1596
                            {
1597
                                SymbolModeling(_symbol, _connSymbol);
1598
                                endModelingGroup.Add(_symbol);
1599
                                break;
1600
                            }
1601
                        }
1602
                    }
1603
                }
1604
            }
1605
        }
1606

    
1607
        /// <summary>
1608
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
1609
        /// </summary>
1610
        /// <param name="childSymbol"></param>
1611
        /// <param name="parentSymbol"></param>
1612
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
1613
        {
1614
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
1615
            double x1 = 0;
1616
            double x2 = 0;
1617
            double y1 = 0;
1618
            double y2 = 0;
1619
            symbol2d.Range(out x1, out y1, out x2, out y2);
1620

    
1621
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
1622
            if (_LMSymbol != null)
1623
            {
1624
                _LMSymbol.Commit();
1625
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1626
                foreach (var item in childSymbol.ChildSymbols)
1627
                    CreateChildSymbol(item, _LMSymbol, parent);
1628
            }
1629

    
1630

    
1631
            ReleaseCOMObjects(_LMSymbol);
1632
        }
1633
        double index = 0;
1634
        private void NewLineModeling(Line line, bool isBranchModeling = false)
1635
        {
1636
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
1637
                return;
1638

    
1639
            List<Line> group = new List<Line>();
1640
            GetConnectedLineGroup(line, group);
1641
            LineCoordinateCorrection(group);
1642

    
1643
            foreach (var groupLine in group)
1644
            {
1645
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
1646
                {
1647
                    BranchLines.Add(groupLine);
1648
                    continue;
1649
                }
1650

    
1651
                bool diagonal = false;
1652
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
1653
                    diagonal = true;
1654
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
1655
                LMSymbol _LMSymbolStart = null;
1656
                LMSymbol _LMSymbolEnd = null;
1657
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1658
                foreach (var connector in groupLine.CONNECTORS)
1659
                {
1660
                    double x = 0;
1661
                    double y = 0;
1662
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
1663
                    if (connector.ConnectedObject == null)
1664
                    {
1665
                        placeRunInputs.AddPoint(x, y);
1666
                    }
1667
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
1668
                    {
1669
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
1670
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
1671
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1672
                        {
1673
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
1674
                            if (_LMSymbolStart != null)
1675
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
1676
                            else
1677
                                placeRunInputs.AddPoint(x, y);
1678
                        }
1679
                        else
1680
                        {
1681
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
1682
                            if (_LMSymbolEnd != null)
1683
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
1684
                            else
1685
                                placeRunInputs.AddPoint(x, y);
1686
                        }
1687
                    }
1688
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
1689
                    {
1690
                        Line targetLine = connector.ConnectedObject as Line;
1691
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
1692
                        {
1693
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
1694
                            if (targetConnector != null)
1695
                            {
1696
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
1697
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1698
                            }
1699
                            else
1700
                            {
1701
                                placeRunInputs.AddPoint( x, y);
1702
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1703
                            }
1704
                        }
1705
                        else
1706
                        {
1707
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1708
                            {
1709
                                index += 0.01;
1710
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1711
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1712
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1713
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1714
                                else
1715
                                {
1716
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
1717
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1718
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1719
                                    else
1720
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1721
                                }
1722
                            }
1723

    
1724
                            placeRunInputs.AddPoint(x, y);
1725

    
1726
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
1727
                            {
1728
                                index += 0.01;
1729
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1730
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1731
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1732
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1733
                                else
1734
                                {
1735
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
1736
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1737
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1738
                                    else
1739
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1740
                                }
1741
                            }
1742
                        }
1743
                    }
1744
                }
1745

    
1746
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1747
                if (_lMConnector != null)
1748
                {
1749
                    _lMConnector.Commit();
1750
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
1751
                    bool bRemodelingStart = false;
1752
                    if (_LMSymbolStart != null)
1753
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
1754
                    bool bRemodelingEnd = false;
1755
                    if (_LMSymbolEnd != null)
1756
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
1757

    
1758
                    if (bRemodelingStart || bRemodelingEnd)
1759
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
1760

    
1761
                    FlowMarkModeling(groupLine);
1762
                    LineNumberModelingOnlyOne(groupLine);
1763

    
1764
                    ReleaseCOMObjects(_lMConnector);
1765
                }
1766
                else if (!isBranchModeling)
1767
                {
1768
                    Log.Write("Main Line Modeling : " + groupLine.UID);
1769
                }
1770

    
1771
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
1772
                x.ConnectedObject != null &&
1773
                x.ConnectedObject.GetType() == typeof(Line) &&
1774
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
1775
                .Select(x => x.ConnectedObject)
1776
                .ToList();
1777

    
1778
                foreach (var item in removeLines)
1779
                    RemoveLineForModeling(item as Line);
1780

    
1781
                if (_LMAItem != null)
1782
                    ReleaseCOMObjects(_LMAItem);
1783
                if (placeRunInputs != null)
1784
                    ReleaseCOMObjects(placeRunInputs);
1785
                if (_LMSymbolStart != null)
1786
                    ReleaseCOMObjects(_LMSymbolStart);
1787
                if (_LMSymbolEnd != null)
1788
                    ReleaseCOMObjects(_LMSymbolEnd);
1789

    
1790
                if (isBranchModeling && BranchLines.Contains(groupLine))
1791
                    BranchLines.Remove(groupLine);
1792
            }
1793
        }
1794

    
1795
        private void RemoveLineForModeling(Line line)
1796
        {
1797
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
1798
            if (modelItem != null)
1799
            {
1800
                foreach (LMRepresentation rep in modelItem.Representations)
1801
                {
1802
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
1803
                    {
1804
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
1805
                        dynamic OID = rep.get_GraphicOID().ToString();
1806
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1807
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1808
                        int verticesCount = lineStringGeometry.VertexCount;
1809
                        double[] vertices = null;
1810
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
1811
                        for (int i = 0; i < verticesCount; i++)
1812
                        {
1813
                            double x = 0;
1814
                            double y = 0;
1815
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
1816
                            if (verticesCount == 2 && (x < 0 || y < 0))
1817
                                _placement.PIDRemovePlacement(rep);
1818
                        }
1819
                        ReleaseCOMObjects(_LMConnector);
1820
                    }
1821
                }
1822

    
1823
                ReleaseCOMObjects(modelItem);
1824
            }
1825
        }
1826

    
1827
        private void GetConnectedLineGroup(Line line, List<Line> group)
1828
        {
1829
            if (!group.Contains(line))
1830
                group.Add(line);
1831
            foreach (var connector in line.CONNECTORS)
1832
            {
1833
                if (connector.ConnectedObject != null &&
1834
                    connector.ConnectedObject.GetType() == typeof(Line) &&
1835
                    !group.Contains(connector.ConnectedObject) &&
1836
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
1837
                {
1838
                    Line connLine = connector.ConnectedObject as Line;
1839
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
1840
                    {
1841
                        if (line.CONNECTORS.IndexOf(connector) == 0)
1842
                            group.Insert(0, connLine);
1843
                        else
1844
                            group.Add(connLine);
1845
                        GetConnectedLineGroup(connLine, group);
1846
                    }
1847
                }
1848
            }
1849
        }
1850

    
1851
        private void LineCoordinateCorrection(List<Line> group)
1852
        {
1853
            // 순서대로 전 Item 기준 정렬
1854
            LineCoordinateCorrectionByStart(group);
1855

    
1856
            // 역으로 심볼이 있을 경우 좌표 보정
1857
            LineCoordinateCorrectionForLastLine(group);
1858
        }
1859

    
1860
        private void LineCoordinateCorrectionByStart(List<Line> group)
1861
        {
1862
            for (int i = 0; i < group.Count; i++)
1863
            {
1864
                Line line = group[i];
1865
                if (i == 0)
1866
                {
1867
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1868
                    if (symbolConnector != null)
1869
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
1870
                }
1871
                else if (i != 0)
1872
                {
1873
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
1874
                }
1875
            }
1876
        }
1877

    
1878
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
1879
        {
1880
            Line checkLine = group[group.Count - 1];
1881
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1882
            if (lastSymbolConnector != null)
1883
            {
1884
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
1885
                for (int i = group.Count - 2; i >= 0; i--)
1886
                {
1887
                    Line line = group[i + 1];
1888
                    Line prevLine = group[i];
1889

    
1890
                    // 같으면 보정
1891
                    if (line.SlopeType == prevLine.SlopeType)
1892
                        LineCoordinateCorrectionByConnItem(prevLine, line);
1893
                    else
1894
                    {
1895
                        if (line.SlopeType == SlopeType.HORIZONTAL)
1896
                        {
1897
                            double prevX = 0;
1898
                            double prevY = 0;
1899
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1900
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
1901

    
1902
                            double x = 0;
1903
                            double y = 0;
1904
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1905
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
1906
                        }
1907
                        else if (line.SlopeType == SlopeType.VERTICAL)
1908
                        {
1909
                            double prevX = 0;
1910
                            double prevY = 0;
1911
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1912
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
1913

    
1914
                            double x = 0;
1915
                            double y = 0;
1916
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1917
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
1918
                        }
1919
                        break;
1920
                    }
1921
                }
1922
            }
1923
        }
1924

    
1925
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
1926
        {
1927
            double x = 0;
1928
            double y = 0;
1929
            if (connItem.GetType() == typeof(Symbol))
1930
            {
1931
                Symbol targetSymbol = connItem as Symbol;
1932
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
1933
                if (targetConnector != null)
1934
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
1935
                else
1936
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
1937
            }
1938
            else if (connItem.GetType() == typeof(Line))
1939
            {
1940
                Line targetLine = connItem as Line;
1941
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
1942
            }
1943

    
1944
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
1945
        }
1946

    
1947
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
1948
        {
1949
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1950
            int index = line.CONNECTORS.IndexOf(connector);
1951
            if (index == 0)
1952
            {
1953
                line.SPPID.START_X = x;
1954
                line.SPPID.START_Y = y;
1955
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1956
                    line.SPPID.END_Y = y;
1957
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1958
                    line.SPPID.END_X = x;
1959
            }
1960
            else
1961
            {
1962
                line.SPPID.END_X = x;
1963
                line.SPPID.END_Y = y;
1964
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
1965
                    line.SPPID.START_Y = y;
1966
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
1967
                    line.SPPID.START_X = x;
1968
            }
1969
        }
1970

    
1971
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
1972
        {
1973
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1974
            int index = line.CONNECTORS.IndexOf(connector);
1975
            if (index == 0)
1976
            {
1977
                line.SPPID.START_X = x;
1978
                if (line.SlopeType == SlopeType.VERTICAL)
1979
                    line.SPPID.END_X = x;
1980
            }
1981
            else
1982
            {
1983
                line.SPPID.END_X = x;
1984
                if (line.SlopeType == SlopeType.VERTICAL)
1985
                    line.SPPID.START_X = x;
1986
            }
1987
        }
1988

    
1989
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
1990
        {
1991
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
1992
            int index = line.CONNECTORS.IndexOf(connector);
1993
            if (index == 0)
1994
            {
1995
                line.SPPID.START_Y = y;
1996
                if (line.SlopeType == SlopeType.HORIZONTAL)
1997
                    line.SPPID.END_Y = y;
1998
            }
1999
            else
2000
            {
2001
                line.SPPID.END_Y = y;
2002
                if (line.SlopeType == SlopeType.HORIZONTAL)
2003
                    line.SPPID.START_Y = y;
2004
            }
2005
        }
2006

    
2007
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2008
        {
2009
            if (symbol != null)
2010
            {
2011
                string repID = symbol.AsLMRepresentation().Id;
2012
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2013
                string lineUID = line.UID;
2014

    
2015
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2016
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2017
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2018

    
2019
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2020
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2021
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2022

    
2023
                if (startSpecBreak != null || startEndBreak != null)
2024
                    result = true;
2025
            }
2026
        }
2027

    
2028
        /// <summary>
2029
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2030
        /// </summary>
2031
        /// <param name="lines"></param>
2032
        /// <param name="prevLMConnector"></param>
2033
        /// <param name="startSymbol"></param>
2034
        /// <param name="endSymbol"></param>
2035
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2036
        {
2037
            string symbolPath = string.Empty;
2038
            #region get symbol path
2039
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2040
            symbolPath = GetSPPIDFileName(modelItem);
2041
            ReleaseCOMObjects(modelItem);
2042
            #endregion
2043
            bool diagonal = false;
2044
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2045
                diagonal = true;
2046
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2047
            LMConnector newConnector = null;
2048
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2049
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2050
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2051
            int verticesCount = lineStringGeometry.VertexCount;
2052
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2053

    
2054
            List<double[]> vertices = new List<double[]>();
2055
            for (int i = 1; i <= verticesCount; i++)
2056
            {
2057
                double x = 0;
2058
                double y = 0;
2059
                lineStringGeometry.GetVertex(i, ref x, ref y);
2060
                vertices.Add(new double[] { x, y });
2061
            }
2062

    
2063
            for (int i = 0; i < vertices.Count; i++)
2064
            {
2065
                double[] points = vertices[i];
2066
                // 시작 심볼이 있고 첫번째 좌표일 때
2067
                if (startSymbol != null && i == 0)
2068
                {
2069
                    if (bStart)
2070
                    {
2071
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2072
                        if (slopeType == SlopeType.HORIZONTAL)
2073
                            placeRunInputs.AddPoint(points[0], -0.1);
2074
                        else if (slopeType == SlopeType.VERTICAL)
2075
                            placeRunInputs.AddPoint(-0.1, points[1]);
2076
                        else
2077
                            placeRunInputs.AddPoint(points[0], -0.1);
2078

    
2079
                        placeRunInputs.AddPoint(points[0], points[1]);
2080
                    }
2081
                    else
2082
                    {
2083
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2084
                    }
2085
                }
2086
                // 마지막 심볼이 있고 마지막 좌표일 때
2087
                else if (endSymbol != null && i == vertices.Count - 1)
2088
                {
2089
                    if (bEnd)
2090
                    {
2091
                        placeRunInputs.AddPoint(points[0], points[1]);
2092

    
2093
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2094
                        if (slopeType == SlopeType.HORIZONTAL)
2095
                            placeRunInputs.AddPoint(points[0], -0.1);
2096
                        else if (slopeType == SlopeType.VERTICAL)
2097
                            placeRunInputs.AddPoint(-0.1, points[1]);
2098
                        else
2099
                            placeRunInputs.AddPoint(points[0], -0.1);
2100
                    }
2101
                    else
2102
                    {
2103
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2104
                    }
2105
                }
2106
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2107
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2108
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2109
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2110
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2111
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2112
                else
2113
                    placeRunInputs.AddPoint(points[0], points[1]);
2114
            }
2115

    
2116
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2117
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2118

    
2119
            ReleaseCOMObjects(placeRunInputs);
2120
            ReleaseCOMObjects(_LMAItem);
2121
            ReleaseCOMObjects(modelItem);
2122

    
2123
            if (newConnector != null)
2124
            {
2125
                newConnector.Commit();
2126
                if (startSymbol != null && bStart)
2127
                {
2128
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2129
                    placeRunInputs = new PlaceRunInputs();
2130
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2131
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2132
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2133
                    if (_LMConnector != null)
2134
                    {
2135
                        _LMConnector.Commit();
2136
                        RemoveConnectorForReModelingLine(newConnector);
2137
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2138
                        ReleaseCOMObjects(_LMConnector);
2139
                    }
2140
                    ReleaseCOMObjects(placeRunInputs);
2141
                    ReleaseCOMObjects(_LMAItem);
2142
                }
2143

    
2144
                if (endSymbol != null && bEnd)
2145
                {
2146
                    if (startSymbol != null)
2147
                    {
2148
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2149
                        newConnector = dicVertices.First().Key;
2150
                    }
2151

    
2152
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2153
                    placeRunInputs = new PlaceRunInputs();
2154
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2155
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2156
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2157
                    if (_LMConnector != null)
2158
                    {
2159
                        _LMConnector.Commit();
2160
                        RemoveConnectorForReModelingLine(newConnector);
2161
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2162
                        ReleaseCOMObjects(_LMConnector);
2163
                    }
2164
                    ReleaseCOMObjects(placeRunInputs);
2165
                    ReleaseCOMObjects(_LMAItem);
2166
                }
2167

    
2168
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2169
                ReleaseCOMObjects(newConnector);
2170
            }
2171

    
2172
            ReleaseCOMObjects(modelItem);
2173
        }
2174

    
2175
        /// <summary>
2176
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2177
        /// </summary>
2178
        /// <param name="connector"></param>
2179
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2180
        {
2181
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2182
            foreach (var item in dicVertices)
2183
            {
2184
                if (item.Value.Count == 2)
2185
                {
2186
                    bool result = false;
2187
                    foreach (var point in item.Value)
2188
                    {
2189
                        if (point[0] < 0 || point[1] < 0)
2190
                        {
2191
                            result = true;
2192
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2193
                            break;
2194
                        }
2195
                    }
2196

    
2197
                    if (result)
2198
                        break;
2199
                }
2200
            }
2201
            foreach (var item in dicVertices)
2202
                ReleaseCOMObjects(item.Key);
2203
        }
2204

    
2205
        /// <summary>
2206
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2207
        /// </summary>
2208
        /// <param name="symbol"></param>
2209
        /// <param name="line"></param>
2210
        /// <returns></returns>
2211
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2212
        {
2213
            LMSymbol _LMSymbol = null;
2214
            foreach (var connector in symbol.CONNECTORS)
2215
            {
2216
                if (connector.CONNECTEDITEM == line.UID)
2217
                {
2218
                    if (connector.Index == 0)
2219
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2220
                    else
2221
                    {
2222
                        ChildSymbol child = null;
2223
                        foreach (var childSymbol in symbol.ChildSymbols)
2224
                        {
2225
                            if (childSymbol.Connectors.Contains(connector))
2226
                                child = childSymbol;
2227
                            else
2228
                                child = GetChildSymbolByConnector(childSymbol, connector);
2229

    
2230
                            if (child != null)
2231
                                break;
2232
                        }
2233

    
2234
                        if (child != null)
2235
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2236
                    }
2237

    
2238
                    break;
2239
                }
2240
            }
2241

    
2242
            return _LMSymbol;
2243
        }
2244

    
2245
        /// <summary>
2246
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2247
        /// </summary>
2248
        /// <param name="item"></param>
2249
        /// <param name="connector"></param>
2250
        /// <returns></returns>
2251
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2252
        {
2253
            foreach (var childSymbol in item.ChildSymbols)
2254
            {
2255
                if (childSymbol.Connectors.Contains(connector))
2256
                    return childSymbol;
2257
                else
2258
                    return GetChildSymbolByConnector(childSymbol, connector);
2259
            }
2260

    
2261
            return null;
2262
        }
2263

    
2264
        /// <summary>
2265
        /// EndBreak 모델링 메서드
2266
        /// </summary>
2267
        /// <param name="endBreak"></param>
2268
        private void EndBreakModeling(EndBreak endBreak)
2269
        {
2270
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2271
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2272
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2273

    
2274
            if (targetLMConnector != null)
2275
            {
2276
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2277
                Array array = null;
2278
                if (point != null)
2279
                    array = new double[] { 0, point[0], point[1] };
2280
                else
2281
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2282
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2283
                if (_LmLabelPersist != null)
2284
                {
2285
                    _LmLabelPersist.Commit();
2286
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2287
                    if (_LmLabelPersist.ModelItemObject != null)
2288
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2289
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2290
                    ReleaseCOMObjects(_LmLabelPersist);
2291
                }
2292
                ReleaseCOMObjects(targetLMConnector);
2293
            }
2294
        }
2295

    
2296
        private LMConnector ReModelingLMConnector(LMConnector connector, string changeSymbolPath = null)
2297
        {
2298
            string symbolPath = string.Empty;
2299
            #region get symbol path
2300
            if (string.IsNullOrEmpty(changeSymbolPath))
2301
            {
2302
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2303
                symbolPath = GetSPPIDFileName(modelItem);
2304
                ReleaseCOMObjects(modelItem);
2305
            }
2306
            else
2307
                symbolPath = changeSymbolPath;
2308
            
2309
            #endregion
2310

    
2311
            LMConnector newConnector = null;
2312
            dynamic OID = connector.get_GraphicOID().ToString();
2313
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2314
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2315
            int verticesCount = lineStringGeometry.VertexCount;
2316
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2317
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2318

    
2319
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2320
            {
2321
                double[] vertices = null;
2322
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2323
                double x = 0;
2324
                double y = 0;
2325
                lineStringGeometry.GetVertex(1, ref x, ref y);
2326

    
2327
                string flowDirection = string.Empty;
2328
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2329
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2330
                    flowDirection = flowAttribute.get_Value().ToString();
2331

    
2332
                if (flowDirection == "End 1 is downstream (Outlet)")
2333
                {
2334
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2335
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2336
                    flowDirection = "End 1 is upstream (Inlet)";
2337
                }
2338
                else
2339
                {
2340
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2341
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2342
                }
2343

    
2344
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2345
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2346
                newConnector.Commit();
2347
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2348
                if (!string.IsNullOrEmpty(flowDirection))
2349
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2350
            }
2351
            else
2352
            {
2353
                List<double[]> vertices = new List<double[]>();
2354
                for (int i = 1; i <= verticesCount; i++)
2355
                {
2356
                    double x = 0;
2357
                    double y = 0;
2358
                    lineStringGeometry.GetVertex(i, ref x, ref y);
2359
                    vertices.Add(new double[] { x, y });
2360
                }
2361

    
2362
                for (int i = 0; i < vertices.Count; i++)
2363
                {
2364
                    double[] points = vertices[i];
2365
                    if (i == 0)
2366
                    {
2367
                        if (connector.ConnectItem1SymbolObject != null)
2368
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, points[0], points[1]);
2369
                        else
2370
                            placeRunInputs.AddPoint(points[0], points[1]);
2371
                    }
2372
                    else if (i == vertices.Count - 1)
2373
                    {
2374
                        if (connector.ConnectItem2SymbolObject != null)
2375
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, points[0], points[1]);
2376
                        else
2377
                            placeRunInputs.AddPoint(points[0], points[1]);
2378
                    }
2379
                    else
2380
                        placeRunInputs.AddPoint(points[0], points[1]);
2381
                }
2382

    
2383
                List<Line> lines = SPPIDUtil.FindLinesByModelId(document, connector.ModelItemID);
2384

    
2385
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2386
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2387
                newConnector.Commit();
2388
                foreach (var line in lines)
2389
                    line.SPPID.ModelItemId = newConnector.ModelItemID;
2390
            }
2391

    
2392

    
2393
            return newConnector;
2394
        }
2395

    
2396
        /// <summary>
2397
        /// SpecBreak Modeling 메서드
2398
        /// </summary>
2399
        /// <param name="specBreak"></param>
2400
        private void SpecBreakModeling(SpecBreak specBreak)
2401
        {
2402
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2403
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2404

    
2405
            if (upStreamObj != null &&
2406
                downStreamObj != null)
2407
            {
2408
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2409

    
2410
                if (targetLMConnector != null)
2411
                {
2412
                    foreach (var attribute in specBreak.ATTRIBUTES)
2413
                    {
2414
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2415
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2416
                        {
2417
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2418
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2419
                            Array array = null;
2420
                            if (point != null)
2421
                                array = new double[] { 0, point[0], point[1] };
2422
                            else
2423
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2424
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2425

    
2426
                            if (_LmLabelPersist != null)
2427
                            {
2428
                                _LmLabelPersist.Commit();
2429
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2430
                                if (_LmLabelPersist.ModelItemObject != null)
2431
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2432
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2433
                                ReleaseCOMObjects(_LmLabelPersist);
2434
                            }
2435
                        }
2436
                    }
2437
                    ReleaseCOMObjects(targetLMConnector);
2438
                }
2439
            }
2440
        }
2441

    
2442
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2443
        {
2444
            LMConnector targetConnector = null;
2445
            Symbol targetSymbol = targetObj as Symbol;
2446
            Symbol connectedSymbol = connectedObj as Symbol;
2447
            Line targetLine = targetObj as Line;
2448
            Line connectedLine = connectedObj as Line;
2449
            if (targetSymbol != null && connectedSymbol != null)
2450
            {
2451
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2452
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2453

    
2454
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2455
                {
2456
                    if (connector.get_ItemStatus() != "Active")
2457
                        continue;
2458

    
2459
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2460
                    {
2461
                        targetConnector = connector;
2462
                        break;
2463
                    }
2464
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2465
                    {
2466
                        targetConnector = connector;
2467
                        break;
2468
                    }
2469
                }
2470

    
2471
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2472
                {
2473
                    if (connector.get_ItemStatus() != "Active")
2474
                        continue;
2475

    
2476
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2477
                    {
2478
                        targetConnector = connector;
2479
                        break;
2480
                    }
2481
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2482
                    {
2483
                        targetConnector = connector;
2484
                        break;
2485
                    }
2486
                }
2487

    
2488
                ReleaseCOMObjects(targetLMSymbol);
2489
                ReleaseCOMObjects(connectedLMSymbol);
2490
            }
2491
            else if (targetLine != null && connectedLine != null)
2492
            {
2493
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2494
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2495

    
2496
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2497
                {
2498
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2499
                    {
2500
                        if (targetConnector != null)
2501
                            break;
2502

    
2503
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2504
                        {
2505
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2506

    
2507
                            if (IsConnected(_LMConnector, connectedModelItem))
2508
                                targetConnector = _LMConnector;
2509
                            else
2510
                                ReleaseCOMObjects(_LMConnector);
2511
                        }
2512
                    }
2513

    
2514
                    ReleaseCOMObjects(targetModelItem);
2515
                }
2516
            }
2517
            else
2518
            {
2519
                LMSymbol connectedLMSymbol = null;
2520
                if (connectedSymbol != null)
2521
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2522
                else if (targetSymbol != null)
2523
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2524
                else
2525
                {
2526

    
2527
                }
2528
                LMModelItem targetModelItem = null;
2529
                if (targetLine != null)
2530
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2531
                else if (connectedLine != null)
2532
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2533
                else
2534
                {
2535

    
2536
                }
2537
                if (connectedLMSymbol != null && targetModelItem != null)
2538
                {
2539
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2540
                    {
2541
                        if (connector.get_ItemStatus() != "Active")
2542
                            continue;
2543

    
2544
                        if (IsConnected(connector, targetModelItem))
2545
                        {
2546
                            targetConnector = connector;
2547
                            break;
2548
                        }
2549
                    }
2550

    
2551
                    if (targetConnector == null)
2552
                    {
2553
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2554
                        {
2555
                            if (connector.get_ItemStatus() != "Active")
2556
                                continue;
2557

    
2558
                            if (IsConnected(connector, targetModelItem))
2559
                            {
2560
                                targetConnector = connector;
2561
                                break;
2562
                            }
2563
                        }
2564
                    }
2565
                }
2566

    
2567
            }
2568

    
2569
            return targetConnector;
2570
        }
2571

    
2572
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2573
        {
2574
            double[] result = null;
2575
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2576
            {
2577
                return GetConnectorVertices(targetConnector)[0];
2578
            }
2579
            else
2580
            {
2581
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
2582
                {
2583
                    Line line = connObj as Line;
2584
                    LMConnector connectedConnector = null;
2585
                    int connIndex = 0;
2586
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2587
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
2588

    
2589
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
2590

    
2591
                    ReleaseCOMObjects(modelItem);
2592
                    ReleaseCOMObjects(connectedConnector);
2593

    
2594
                    if (vertices.Count > 0)
2595
                    {
2596
                        if (connIndex == 1)
2597
                            return vertices[0];
2598
                        else if (connIndex == 2)
2599
                            return vertices[vertices.Count - 1];
2600
                    }
2601
                }
2602
                else
2603
                {
2604
                    Log.Write("error in GetSegemtPoint");
2605
                }
2606
            }
2607

    
2608
            return result;
2609
        }
2610

    
2611
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
2612
        {
2613
            bool result = false;
2614

    
2615
            foreach (LMRepresentation rep in modelItem.Representations)
2616
            {
2617
                if (result)
2618
                    break;
2619

    
2620
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2621
                {
2622
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2623

    
2624
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2625
                        connector.ConnectItem1SymbolObject != null &&
2626
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2627
                    {
2628
                        result = true;
2629
                        ReleaseCOMObjects(_LMConnector);
2630
                        break;
2631
                    }
2632
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2633
                        connector.ConnectItem2SymbolObject != null &&
2634
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2635
                    {
2636
                        result = true;
2637
                        ReleaseCOMObjects(_LMConnector);
2638
                        break;
2639
                    }
2640
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2641
                        connector.ConnectItem1SymbolObject != null &&
2642
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2643
                    {
2644
                        result = true;
2645
                        ReleaseCOMObjects(_LMConnector);
2646
                        break;
2647
                    }
2648
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2649
                        connector.ConnectItem2SymbolObject != null &&
2650
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2651
                    {
2652
                        result = true;
2653
                        ReleaseCOMObjects(_LMConnector);
2654
                        break;
2655
                    }
2656

    
2657
                    ReleaseCOMObjects(_LMConnector);
2658
                }
2659
            }
2660

    
2661

    
2662
            return result;
2663
        }
2664

    
2665
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
2666
        {
2667
            foreach (LMRepresentation rep in modelItem.Representations)
2668
            {
2669
                if (connectedConnector != null)
2670
                    break;
2671

    
2672
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2673
                {
2674
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2675

    
2676
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2677
                        connector.ConnectItem1SymbolObject != null &&
2678
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2679
                    {
2680
                        connectedConnector = _LMConnector;
2681
                        connectorIndex = 1;
2682
                        break;
2683
                    }
2684
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2685
                        connector.ConnectItem2SymbolObject != null &&
2686
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2687
                    {
2688
                        connectedConnector = _LMConnector;
2689
                        connectorIndex = 2;
2690
                        break;
2691
                    }
2692
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2693
                        connector.ConnectItem1SymbolObject != null &&
2694
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2695
                    {
2696
                        connectedConnector = _LMConnector;
2697
                        connectorIndex = 1;
2698
                        break;
2699
                    }
2700
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2701
                        connector.ConnectItem2SymbolObject != null &&
2702
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2703
                    {
2704
                        connectedConnector = _LMConnector;
2705
                        connectorIndex = 2;
2706
                        break;
2707
                    }
2708

    
2709
                    if (connectedConnector == null)
2710
                        ReleaseCOMObjects(_LMConnector);
2711
                }
2712
            }
2713
        }
2714

    
2715
        /// <summary>
2716
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
2717
        /// </summary>
2718
        /// <param name="modelItemID1"></param>
2719
        /// <param name="modelItemID2"></param>
2720
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
2721
        {
2722
            try
2723
            {
2724
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
2725
                _LMAItem item1 = modelItem1.AsLMAItem();
2726
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
2727
                _LMAItem item2 = modelItem2.AsLMAItem();
2728

    
2729
                // item2가 item1으로 조인
2730
                _placement.PIDJoinRuns(ref item1, ref item2);
2731
                item1.Commit();
2732
                item2.Commit();
2733

    
2734
                string beforeID = string.Empty;
2735
                string afterID = string.Empty;
2736

    
2737
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
2738
                {
2739
                    beforeID = modelItem2.Id;
2740
                    afterID = modelItem1.Id;
2741
                    survivorId = afterID;
2742
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
2743
                    if (attribute != null)
2744
                        attribute.set_Value("End 1 is upstream (Inlet)");
2745
                }
2746
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
2747
                {
2748
                    beforeID = modelItem1.Id;
2749
                    afterID = modelItem2.Id;
2750
                    survivorId = afterID;
2751
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
2752
                    if (attribute != null)
2753
                        attribute.set_Value("End 1 is upstream (Inlet)");
2754
                }
2755
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
2756
                    survivorId = null;
2757
                else
2758
                {
2759
                    Log.Write("잘못된 경우");
2760
                    survivorId = null;
2761
                }
2762

    
2763
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
2764
                {
2765
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
2766
                    foreach (var line in lines)
2767
                        line.SPPID.ModelItemId = afterID;
2768
                }
2769

    
2770
                ReleaseCOMObjects(modelItem1);
2771
                ReleaseCOMObjects(item1);
2772
                ReleaseCOMObjects(modelItem2);
2773
                ReleaseCOMObjects(item2);
2774
            }
2775
            catch (Exception ex)
2776
            {
2777
                Log.Write("Join Error");
2778
                Log.Write(ex.Message);
2779
            }
2780
        }
2781

    
2782
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
2783
        {
2784
            List<string> modelItemIDs = new List<string>();
2785
            foreach (LMConnector connector in symbol.Avoid1Connectors)
2786
            {
2787
                LMModelItem modelItem = connector.ModelItemObject;
2788
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2789
                    modelItemIDs.Add(modelItem.Id);
2790
                ReleaseCOMObjects(modelItem);
2791
                ReleaseCOMObjects(connector);
2792
            }
2793

    
2794
            foreach (LMConnector connector in symbol.Avoid2Connectors)
2795
            {
2796
                LMModelItem modelItem = connector.ModelItemObject;
2797
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2798
                    modelItemIDs.Add(modelItem.Id);
2799
                ReleaseCOMObjects(modelItem);
2800
                ReleaseCOMObjects(connector);
2801
            }
2802

    
2803

    
2804
            List<string> result = new List<string>();
2805
            modelItemIDs = modelItemIDs.Distinct().ToList();
2806
            string originalName = GetSPPIDFileName(modelId);
2807
            foreach (var item in modelItemIDs)
2808
            {
2809
                string fileName = GetSPPIDFileName(item);
2810
                if (originalName == fileName)
2811
                    result.Add(item);
2812
                else
2813
                {
2814
                    LMConnector connector = GetLMConnectorOnlyOne(item);
2815
                    if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()))
2816
                    {
2817
                        result.Add(item);
2818
                        ReleaseCOMObjects(connector);
2819
                    }
2820
                }
2821
            }
2822
            
2823
            return result;
2824
        }
2825

    
2826
        /// <summary>
2827
        /// PipeRun의 좌표를 가져오는 메서드
2828
        /// </summary>
2829
        /// <param name="modelId"></param>
2830
        /// <returns></returns>
2831
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId)
2832
        {
2833
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
2834
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
2835

    
2836
            if (modelItem != null)
2837
            {
2838
                foreach (LMRepresentation rep in modelItem.Representations)
2839
                {
2840
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2841
                    {
2842
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2843
                        connectorVertices.Add(_LMConnector, new List<double[]>());
2844
                        dynamic OID = rep.get_GraphicOID().ToString();
2845
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2846
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2847
                        int verticesCount = lineStringGeometry.VertexCount;
2848
                        double[] vertices = null;
2849
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2850
                        for (int i = 0; i < verticesCount; i++)
2851
                        {
2852
                            double x = 0;
2853
                            double y = 0;
2854
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2855
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
2856
                        }
2857
                    }
2858
                }
2859

    
2860
                ReleaseCOMObjects(modelItem);
2861
            }
2862

    
2863
            return connectorVertices;
2864
        }
2865

    
2866
        private List<double[]> GetConnectorVertices(LMConnector connector)
2867
        {
2868
            List<double[]> vertices = new List<double[]>();
2869
            if (connector != null)
2870
            {
2871
                dynamic OID = connector.get_GraphicOID().ToString();
2872
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2873
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2874
                int verticesCount = lineStringGeometry.VertexCount;
2875
                double[] value = null;
2876
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
2877
                for (int i = 0; i < verticesCount; i++)
2878
                {
2879
                    double x = 0;
2880
                    double y = 0;
2881
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2882
                    vertices.Add(new double[] { x, y });
2883
                }
2884
            }
2885
            return vertices;
2886
        }
2887

    
2888
        /// <summary>
2889
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
2890
        /// </summary>
2891
        /// <param name="connectorVertices"></param>
2892
        /// <param name="connX"></param>
2893
        /// <param name="connY"></param>
2894
        /// <returns></returns>
2895
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
2896
        {
2897
            double length = double.MaxValue;
2898
            LMConnector targetConnector = null;
2899
            foreach (var item in connectorVertices)
2900
            {
2901
                List<double[]> points = item.Value;
2902
                for (int i = 0; i < points.Count - 1; i++)
2903
                {
2904
                    double[] point1 = points[i];
2905
                    double[] point2 = points[i + 1];
2906
                    double x1 = Math.Min(point1[0], point2[0]);
2907
                    double y1 = Math.Min(point1[1], point2[1]);
2908
                    double x2 = Math.Max(point1[0], point2[0]);
2909
                    double y2 = Math.Max(point1[1], point2[1]);
2910

    
2911
                    if ((x1 <= connX && x2 >= connX) ||
2912
                        (y1 <= connY && y2 >= connY))
2913
                    {
2914
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
2915
                        if (length >= distance)
2916
                        {
2917
                            targetConnector = item.Key;
2918
                            length = distance;
2919
                        }
2920

    
2921
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
2922
                        if (length >= distance)
2923
                        {
2924
                            targetConnector = item.Key;
2925
                            length = distance;
2926
                        }
2927
                    }
2928
                }
2929
            }
2930

    
2931
            // 못찾았을때.
2932
            length = double.MaxValue;
2933
            if (targetConnector == null)
2934
            {
2935
                foreach (var item in connectorVertices)
2936
                {
2937
                    List<double[]> points = item.Value;
2938

    
2939
                    foreach (double[] point in points)
2940
                    {
2941
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
2942
                        if (length >= distance)
2943
                        {
2944
                            targetConnector = item.Key;
2945
                            length = distance;
2946
                        }
2947
                    }
2948
                }
2949
            }
2950

    
2951
            return targetConnector;
2952
        }
2953

    
2954
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
2955
        {
2956
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
2957
            if (vertices.Count == 0)
2958
                return null;
2959

    
2960
            double length = double.MaxValue;
2961
            LMConnector targetConnector = null;
2962
            double[] resultPoint = null;
2963
            List<double[]> targetVertices = null;
2964

    
2965
            // Vertices 포인트에 제일 가까운곳
2966
            foreach (var item in vertices)
2967
            {
2968
                List<double[]> points = item.Value;
2969
                for (int i = 0; i < points.Count; i++)
2970
                {
2971
                    double[] point = points[i];
2972
                    double tempX = point[0];
2973
                    double tempY = point[1];
2974

    
2975
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
2976
                    if (length >= distance)
2977
                    {
2978
                        targetConnector = item.Key;
2979
                        length = distance;
2980
                        resultPoint = point;
2981
                        targetVertices = item.Value;
2982
                    }
2983
                }
2984
            }
2985

    
2986
            // Vertices Cross에 제일 가까운곳
2987
            foreach (var item in vertices)
2988
            {
2989
                List<double[]> points = item.Value;
2990
                for (int i = 0; i < points.Count - 1; i++)
2991
                {
2992
                    double[] point1 = points[i];
2993
                    double[] point2 = points[i + 1];
2994

    
2995
                    double maxLineX = Math.Max(point1[0], point2[0]);
2996
                    double minLineX = Math.Min(point1[0], point2[0]);
2997
                    double maxLineY = Math.Max(point1[1], point2[1]);
2998
                    double minLineY = Math.Min(point1[1], point2[1]);
2999

    
3000
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3001

    
3002
                    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]);
3003
                    if (crossingPoint != null)
3004
                    {
3005
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3006
                        if (length >= distance)
3007
                        {
3008
                            if (slope == SlopeType.Slope &&
3009
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3010
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3011
                            {
3012
                                targetConnector = item.Key;
3013
                                length = distance;
3014
                                resultPoint = crossingPoint;
3015
                                targetVertices = item.Value;
3016
                            }
3017
                            else if (slope == SlopeType.HORIZONTAL &&
3018
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3019
                            {
3020
                                targetConnector = item.Key;
3021
                                length = distance;
3022
                                resultPoint = crossingPoint;
3023
                                targetVertices = item.Value;
3024
                            }
3025
                            else if (slope == SlopeType.VERTICAL &&
3026
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3027
                            {
3028
                                targetConnector = item.Key;
3029
                                length = distance;
3030
                                resultPoint = crossingPoint;
3031
                                targetVertices = item.Value;
3032
                            }
3033
                        }
3034
                    }
3035
                }
3036
            }
3037

    
3038
            foreach (var item in vertices)
3039
                if (item.Key != null && item.Key != targetConnector)
3040
                    ReleaseCOMObjects(item.Key);
3041

    
3042
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3043
            {
3044
                double tempResultX = resultPoint[0];
3045
                double tempResultY = resultPoint[1];
3046
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3047

    
3048
                GridSetting gridSetting = GridSetting.GetInstance();
3049

    
3050
                for (int i = 0; i < targetVertices.Count; i++)
3051
                {
3052
                    double[] point = targetVertices[i];
3053
                    double tempX = targetVertices[i][0];
3054
                    double tempY = targetVertices[i][1];
3055
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3056
                    if (tempX == tempResultX && tempY == tempResultY)
3057
                    {
3058
                        if (i == 0)
3059
                        {
3060
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3061
                            bool containZeroLength = false;
3062
                            if (connSymbol != null)
3063
                            {
3064
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3065
                                {
3066
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3067
                                        containZeroLength = true;
3068
                                }
3069
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3070
                                {
3071
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3072
                                        containZeroLength = true;
3073
                                }
3074
                            }
3075

    
3076
                            if (connSymbol == null ||
3077
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3078
                                containZeroLength)
3079
                            {
3080
                                bool bCalcX = false;
3081
                                bool bCalcY = false;
3082
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3083
                                    bCalcX = true;
3084
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3085
                                    bCalcY = true;
3086
                                else
3087
                                {
3088
                                    bCalcX = true;
3089
                                    bCalcY = true;
3090
                                }
3091

    
3092
                                if (bCalcX)
3093
                                {
3094
                                    double nextX = targetVertices[i + 1][0];
3095
                                    double newX = 0;
3096
                                    if (nextX > tempX)
3097
                                    {
3098
                                        newX = tempX + gridSetting.Length;
3099
                                        if (newX > nextX)
3100
                                            newX = (point[0] + nextX) / 2;
3101
                                    }
3102
                                    else
3103
                                    {
3104
                                        newX = tempX - gridSetting.Length;
3105
                                        if (newX < nextX)
3106
                                            newX = (point[0] + nextX) / 2;
3107
                                    }
3108
                                    resultPoint = new double[] { newX, resultPoint[1] };
3109
                                }
3110

    
3111
                                if (bCalcY)
3112
                                {
3113
                                    double nextY = targetVertices[i + 1][1];
3114
                                    double newY = 0;
3115
                                    if (nextY > tempY)
3116
                                    {
3117
                                        newY = tempY + gridSetting.Length;
3118
                                        if (newY > nextY)
3119
                                            newY = (point[1] + nextY) / 2;
3120
                                    }
3121
                                    else
3122
                                    {
3123
                                        newY = tempY - gridSetting.Length;
3124
                                        if (newY < nextY)
3125
                                            newY = (point[1] + nextY) / 2;
3126
                                    }
3127
                                    resultPoint = new double[] { resultPoint[0], newY };
3128
                                }
3129
                            }
3130
                        }
3131
                        else if (i == targetVertices.Count - 1)
3132
                        {
3133
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3134
                            bool containZeroLength = false;
3135
                            if (connSymbol != null)
3136
                            {
3137
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3138
                                {
3139
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3140
                                        containZeroLength = true;
3141
                                }
3142
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3143
                                {
3144
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3145
                                        containZeroLength = true;
3146
                                }
3147
                            }
3148

    
3149
                            if (connSymbol == null ||
3150
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3151
                                containZeroLength)
3152
                            {
3153
                                bool bCalcX = false;
3154
                                bool bCalcY = false;
3155
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3156
                                    bCalcX = true;
3157
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3158
                                    bCalcY = true;
3159
                                else
3160
                                {
3161
                                    bCalcX = true;
3162
                                    bCalcY = true;
3163
                                }
3164

    
3165
                                if (bCalcX)
3166
                                {
3167
                                    double nextX = targetVertices[i - 1][0];
3168
                                    double newX = 0;
3169
                                    if (nextX > tempX)
3170
                                    {
3171
                                        newX = tempX + gridSetting.Length;
3172
                                        if (newX > nextX)
3173
                                            newX = (point[0] + nextX) / 2;
3174
                                    }
3175
                                    else
3176
                                    {
3177
                                        newX = tempX - gridSetting.Length;
3178
                                        if (newX < nextX)
3179
                                            newX = (point[0] + nextX) / 2;
3180
                                    }
3181
                                    resultPoint = new double[] { newX, resultPoint[1] };
3182
                                }
3183

    
3184
                                if (bCalcY)
3185
                                {
3186
                                    double nextY = targetVertices[i - 1][1];
3187
                                    double newY = 0;
3188
                                    if (nextY > tempY)
3189
                                    {
3190
                                        newY = tempY + gridSetting.Length;
3191
                                        if (newY > nextY)
3192
                                            newY = (point[1] + nextY) / 2;
3193
                                    }
3194
                                    else
3195
                                    {
3196
                                        newY = tempY - gridSetting.Length;
3197
                                        if (newY < nextY)
3198
                                            newY = (point[1] + nextY) / 2;
3199
                                    }
3200
                                    resultPoint = new double[] { resultPoint[0], newY };
3201
                                }
3202
                            }
3203
                        }
3204
                        break;
3205
                    }
3206
                }
3207
            }
3208

    
3209
            x = resultPoint[0];
3210
            y = resultPoint[1];
3211

    
3212
            return targetConnector;
3213
        }
3214

    
3215
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3216
        {
3217
            LMConnector result = null;
3218
            List<LMConnector> connectors = new List<LMConnector>();
3219
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3220

    
3221
            if (modelItem != null)
3222
            {
3223
                foreach (LMRepresentation rep in modelItem.Representations)
3224
                {
3225
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3226
                        connectors.Add(dataSource.GetConnector(rep.Id));
3227
                }
3228

    
3229
                ReleaseCOMObjects(modelItem);
3230
            }
3231

    
3232
            if (connectors.Count == 1)
3233
                result = connectors[0];
3234
            else
3235
                foreach (var item in connectors)
3236
                    ReleaseCOMObjects(item);
3237

    
3238
            return result;
3239
        }
3240

    
3241
        /// <summary>
3242
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3243
        /// </summary>
3244
        /// <param name="lineNumber"></param>
3245
        private void LineNumberModelingOnlyOne(Line line)
3246
        {
3247
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3248
            if (lineNumber != null)
3249
            {
3250
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3251
                if (connectedLMConnector != null)
3252
                {
3253
                    double x = 0;
3254
                    double y = 0;
3255
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3256

    
3257
                    Array points = new double[] { 0, x, y };
3258
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3259

    
3260
                    if (_LmLabelPresist != null)
3261
                    {
3262
                        _LmLabelPresist.Commit();
3263
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3264
                        ReleaseCOMObjects(_LmLabelPresist);
3265
                    }
3266
                }
3267
            }
3268
        }
3269

    
3270
        private void LineNumberModeling(LineNumber lineNumber)
3271
        {
3272
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3273
            if (line != null)
3274
            {
3275
                double x = 0;
3276
                double y = 0;
3277
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3278

    
3279
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3280
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3281
                if (connectedLMConnector != null)
3282
                {
3283
                    Array points = new double[] { 0, x, y };
3284
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3285

    
3286
                    if (_LmLabelPresist != null)
3287
                    {
3288
                        _LmLabelPresist.Commit();
3289
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3290
                        ReleaseCOMObjects(_LmLabelPresist);
3291
                    }
3292
                }
3293

    
3294
                foreach (var item in connectorVertices)
3295
                    ReleaseCOMObjects(item.Key);
3296
            }
3297
        }
3298
        /// <summary>
3299
        /// Flow Mark Modeling
3300
        /// </summary>
3301
        /// <param name="line"></param>
3302
        private void FlowMarkModeling(Line line)
3303
        {
3304
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3305
            {
3306
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3307
                if (connector != null)
3308
                {
3309
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
3310
                    List<double[]> vertices = GetConnectorVertices(connector);
3311
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
3312
                    double[] point = vertices[vertices.Count - 1];
3313
                    Array array = new double[] { 0, point[0], point[1] };
3314
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
3315
                    if (_LMLabelPersist != null)
3316
                    {
3317
                        _LMLabelPersist.Commit();
3318
                        ReleaseCOMObjects(_LMLabelPersist);
3319
                    }
3320
                        
3321
                }
3322
            }
3323
        }
3324

    
3325
        /// <summary>
3326
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
3327
        /// </summary>
3328
        /// <param name="lineNumber"></param>
3329
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
3330
        {
3331
            foreach (LineRun run in lineNumber.RUNS)
3332
            {
3333
                foreach (var item in run.RUNITEMS)
3334
                {
3335
                    if (item.GetType() == typeof(Symbol))
3336
                    {
3337
                        Symbol symbol = item as Symbol;
3338
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3339
                        if (_LMSymbol != null)
3340
                        {
3341
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3342

    
3343
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3344
                            {
3345
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3346
                                {
3347
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3348
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3349
                                    {
3350
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3351
                                        if (_LMAAttribute != null)
3352
                                        {
3353
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3354
                                                _LMAAttribute.set_Value(attribute.VALUE);
3355
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3356
                                                _LMAAttribute.set_Value(attribute.VALUE);
3357
                                        }
3358
                                    }
3359
                                }
3360
                                _LMModelItem.Commit();
3361
                            }
3362
                            if (_LMModelItem != null)
3363
                                ReleaseCOMObjects(_LMModelItem);
3364
                        }
3365
                        if (_LMSymbol != null)
3366
                            ReleaseCOMObjects(_LMSymbol);
3367
                    }
3368
                    else if (item.GetType() == typeof(Line))
3369
                    {
3370
                        Line line = item as Line;
3371
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
3372
                        {
3373
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3374
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3375
                            {
3376
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3377
                                {
3378
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3379
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3380
                                    {
3381
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3382
                                        if (_LMAAttribute != null)
3383
                                        {
3384
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3385
                                                _LMAAttribute.set_Value(attribute.VALUE);
3386
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3387
                                                _LMAAttribute.set_Value(attribute.VALUE);
3388

    
3389
                                        }
3390
                                    }
3391
                                }
3392
                                _LMModelItem.Commit();
3393
                            }
3394
                            if (_LMModelItem != null)
3395
                                ReleaseCOMObjects(_LMModelItem);
3396
                            endLine.Add(line.SPPID.ModelItemId);
3397
                        }
3398
                    }
3399
                }
3400
            }
3401
        }
3402

    
3403
        /// <summary>
3404
        /// Symbol Attribute 입력 메서드
3405
        /// </summary>
3406
        /// <param name="item"></param>
3407
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
3408
        {
3409
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
3410
            string sRep = null;
3411
            if (targetItem.GetType() == typeof(Symbol))
3412
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
3413
            else if (targetItem.GetType() == typeof(Equipment))
3414
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
3415

    
3416
            if (!string.IsNullOrEmpty(sRep))
3417
            {
3418
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
3419
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3420
                LMAAttributes _Attributes = _LMModelItem.Attributes;
3421
                
3422
                foreach (var item in targetAttributes)
3423
                {
3424
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
3425
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
3426
                    {
3427
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
3428
                        if (_Attribute != null)
3429
                        {
3430
                            object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
3431
                            if (associItem != null)
3432
                            {
3433
                                if (associItem.GetType() == typeof(Text))
3434
                                {
3435
                                    Text text = associItem as Text;
3436
                                    text.SPPID.RepresentationId = "Attribute";
3437
                                }
3438
                                else if (associItem.GetType() == typeof(Note))
3439
                                {
3440
                                    Note note = associItem as Note;
3441
                                    note.SPPID.RepresentationId = "Attribute";
3442
                                }
3443
                            }
3444
                            _Attribute.set_Value(item.VALUE);
3445
                        }
3446
                            
3447
                    }
3448
                }
3449
                _LMModelItem.Commit();
3450

    
3451
                ReleaseCOMObjects(_Attributes);
3452
                ReleaseCOMObjects(_LMModelItem);
3453
                ReleaseCOMObjects(_LMSymbol);
3454
            }
3455
        }
3456

    
3457
        /// <summary>
3458
        /// Input SpecBreak Attribute
3459
        /// </summary>
3460
        /// <param name="specBreak"></param>
3461
        private void InputSpecBreakAttribute(SpecBreak specBreak)
3462
        {
3463
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3464
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3465

    
3466
            if (upStreamObj != null &&
3467
                downStreamObj != null)
3468
            {
3469
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3470

    
3471
                if (targetLMConnector != null)
3472
                {
3473
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
3474
                    {
3475
                        string symbolPath = _LMLabelPersist.get_FileName();
3476
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
3477
                        if (mapping != null)
3478
                        {
3479
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
3480
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3481
                            {
3482
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
3483
                                if (values.Length == 2)
3484
                                {
3485
                                    string upStreamValue = values[0];
3486
                                    string downStreamValue = values[1];
3487

    
3488
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
3489
                                }
3490
                            }
3491
                        }
3492
                    }
3493

    
3494
                    ReleaseCOMObjects(targetLMConnector);
3495
                }
3496
            }
3497

    
3498

    
3499
            #region 내부에서만 쓰는 메서드
3500
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
3501
            {
3502
                Symbol upStreamSymbol = _upStreamObj as Symbol;
3503
                Line upStreamLine = _upStreamObj as Line;
3504
                Symbol downStreamSymbol = _downStreamObj as Symbol;
3505
                Line downStreamLine = _downStreamObj as Line;
3506
                // 둘다 Line일 경우
3507
                if (upStreamLine != null && downStreamLine != null)
3508
                {
3509
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3510
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3511
                }
3512
                // 둘다 Symbol일 경우
3513
                else if (upStreamSymbol != null && downStreamSymbol != null)
3514
                {
3515
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
3516
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3517
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3518

    
3519
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3520
                    {
3521
                        if (connector.get_ItemStatus() != "Active")
3522
                            continue;
3523

    
3524
                        if (connector.Id != zeroLenthConnector.Id)
3525
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3526
                    }
3527

    
3528
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3529
                    {
3530
                        if (connector.get_ItemStatus() != "Active")
3531
                            continue;
3532

    
3533
                        if (connector.Id != zeroLenthConnector.Id)
3534
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3535
                    }
3536

    
3537
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3538
                    {
3539
                        if (connector.get_ItemStatus() != "Active")
3540
                            continue;
3541

    
3542
                        if (connector.Id != zeroLenthConnector.Id)
3543
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3544
                    }
3545

    
3546
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3547
                    {
3548
                        if (connector.get_ItemStatus() != "Active")
3549
                            continue;
3550

    
3551
                        if (connector.Id != zeroLenthConnector.Id)
3552
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3553
                    }
3554

    
3555
                    ReleaseCOMObjects(zeroLenthConnector);
3556
                    ReleaseCOMObjects(upStreamLMSymbol);
3557
                    ReleaseCOMObjects(downStreamLMSymbol);
3558
                }
3559
                else if (upStreamSymbol != null && downStreamLine != null)
3560
                {
3561
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
3562
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3563
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3564

    
3565
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3566
                    {
3567
                        if (connector.get_ItemStatus() != "Active")
3568
                            continue;
3569

    
3570
                        if (connector.Id == zeroLenthConnector.Id)
3571
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3572
                    }
3573

    
3574
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3575
                    {
3576
                        if (connector.get_ItemStatus() != "Active")
3577
                            continue;
3578

    
3579
                        if (connector.Id == zeroLenthConnector.Id)
3580
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3581
                    }
3582

    
3583
                    ReleaseCOMObjects(zeroLenthConnector);
3584
                    ReleaseCOMObjects(upStreamLMSymbol);
3585
                }
3586
                else if (upStreamLine != null && downStreamSymbol != null)
3587
                {
3588
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
3589
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3590
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3591

    
3592
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3593
                    {
3594
                        if (connector.get_ItemStatus() != "Active")
3595
                            continue;
3596

    
3597
                        if (connector.Id == zeroLenthConnector.Id)
3598
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3599
                    }
3600

    
3601
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3602
                    {
3603
                        if (connector.get_ItemStatus() != "Active")
3604
                            continue;
3605

    
3606
                        if (connector.Id == zeroLenthConnector.Id)
3607
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3608
                    }
3609

    
3610
                    ReleaseCOMObjects(zeroLenthConnector);
3611
                    ReleaseCOMObjects(downStreamLMSymbol);
3612
                }
3613
            }
3614

    
3615
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
3616
            {
3617
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3618
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3619
                {
3620
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3621
                    if (_LMAAttribute != null)
3622
                    {
3623
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3624
                            _LMAAttribute.set_Value(value);
3625
                        else if (_LMAAttribute.get_Value() != value)
3626
                            _LMAAttribute.set_Value(value);
3627
                    }
3628

    
3629
                    _LMModelItem.Commit();
3630
                }
3631
                if (_LMModelItem != null)
3632
                    ReleaseCOMObjects(_LMModelItem);
3633
            }
3634

    
3635
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
3636
            {
3637
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
3638
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3639
                {
3640
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3641
                    if (_LMAAttribute != null)
3642
                    {
3643
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3644
                            _LMAAttribute.set_Value(value);
3645
                        else if (_LMAAttribute.get_Value() != value)
3646
                            _LMAAttribute.set_Value(value);
3647
                    }
3648

    
3649
                    _LMModelItem.Commit();
3650
                }
3651
                if (_LMModelItem != null)
3652
                    ReleaseCOMObjects(_LMModelItem);
3653
            }
3654
            #endregion
3655
        }
3656

    
3657
        /// <summary>
3658
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
3659
        /// </summary>
3660
        /// <param name="text"></param>
3661
        private void TextModeling(Text text)
3662
        {
3663
            LMSymbol _LMSymbol = null;
3664
            LMConnector connectedLMConnector = null;
3665
            //if (text.ASSOCIATION && !string.IsNullOrEmpty(text.OWNER) && text.OWNER != "None")
3666
            if (text.ASSOCIATION)
3667
            {
3668
                object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
3669
                if (owner != null && owner.GetType() == typeof(Symbol))
3670
                {
3671
                    Symbol symbol = owner as Symbol;
3672
                    _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3673
                    if (_LMSymbol != null)
3674
                    {
3675
                        BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3676
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3677
                        {
3678
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3679

    
3680
                            if (mapping != null)
3681
                            {
3682
                                double x = 0;
3683
                                double y = 0;
3684

    
3685
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3686
                                Array array = new double[] { 0, x, y };
3687

    
3688
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3689
                                if (_LMLabelPersist != null)
3690
                                {
3691
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3692
                                    _LMLabelPersist.Commit();
3693
                                    ReleaseCOMObjects(_LMLabelPersist);
3694
                                }
3695
                            }
3696
                        }
3697
                    }
3698
                }
3699
                else if (owner != null && owner.GetType() == typeof(Line))
3700
                {
3701
                    Line line = owner as Line;
3702
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3703
                    connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
3704

    
3705
                    if (connectedLMConnector != null)
3706
                    {
3707
                        BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3708
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3709
                        {
3710
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3711

    
3712
                            if (mapping != null)
3713
                            {
3714
                                double x = 0;
3715
                                double y = 0;
3716

    
3717
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3718
                                Array array = new double[] { 0, x, y };
3719

    
3720
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3721
                                if (_LMLabelPersist != null)
3722
                                {
3723
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3724
                                    _LMLabelPersist.Commit();
3725
                                    ReleaseCOMObjects(_LMLabelPersist);
3726
                                }
3727
                            }
3728
                        }
3729
                    }
3730
                }
3731
            }
3732
            else
3733
            {
3734
                LMItemNote _LMItemNote = null;
3735
                LMAAttribute _LMAAttribute = null;
3736

    
3737
                double x = 0;
3738
                double y = 0;
3739
                double angle = text.ANGLE;
3740
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
3741

    
3742
                _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
3743
                if (_LMSymbol != null)
3744
                {
3745
                    _LMSymbol.Commit();
3746
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3747
                    if (_LMItemNote != null)
3748
                    {
3749
                        _LMItemNote.Commit();
3750
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3751
                        if (_LMAAttribute != null)
3752
                        {
3753
                            _LMAAttribute.set_Value(text.VALUE);
3754
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3755
                            _LMItemNote.Commit();
3756

    
3757
                            if (_LMAAttribute != null)
3758
                                ReleaseCOMObjects(_LMAAttribute);
3759
                            if (_LMItemNote != null)
3760
                                ReleaseCOMObjects(_LMItemNote);
3761
                        }
3762
                    }
3763
                }
3764
            }
3765
            if (_LMSymbol != null)
3766
                ReleaseCOMObjects(_LMSymbol);
3767
        }
3768

    
3769
        /// <summary>
3770
        /// Note Modeling
3771
        /// </summary>
3772
        /// <param name="note"></param>
3773
        private void NoteModeling(Note note)
3774
        {
3775
            LMSymbol _LMSymbol = null;
3776
            LMItemNote _LMItemNote = null;
3777
            LMAAttribute _LMAAttribute = null;
3778

    
3779
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
3780
            {
3781
                double x = 0;
3782
                double y = 0;
3783

    
3784
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
3785

    
3786
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
3787
                if (_LMSymbol != null)
3788
                {
3789
                    _LMSymbol.Commit();
3790
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3791
                    if (_LMItemNote != null)
3792
                    {
3793
                        _LMItemNote.Commit();
3794
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3795
                        if (_LMAAttribute != null)
3796
                        {
3797
                            _LMAAttribute.set_Value(note.VALUE);
3798
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3799
                            _LMItemNote.Commit();
3800
                        }
3801
                    }
3802
                }
3803
            }
3804

    
3805
            if (_LMAAttribute != null)
3806
                ReleaseCOMObjects(_LMAAttribute);
3807
            if (_LMItemNote != null)
3808
                ReleaseCOMObjects(_LMItemNote);
3809
            if (_LMSymbol != null)
3810
                ReleaseCOMObjects(_LMSymbol);
3811
        }
3812

    
3813
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
3814
        {
3815
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
3816
            if (modelItem != null)
3817
            {
3818
                foreach (LMRepresentation rep in modelItem.Representations)
3819
                {
3820
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3821
                    {
3822
                        LMConnector connector = dataSource.GetConnector(rep.Id);
3823
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
3824
                        {
3825
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
3826
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3827
                            if (modelItemIds.Count == 1)
3828
                            {
3829
                                string joinModelItemId = modelItemIds[0];
3830
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3831
                                if (survivorId != null)
3832
                                    break;
3833
                            }
3834
                        }
3835
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
3836
                        {
3837
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
3838
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
3839
                            if (modelItemIds.Count == 1)
3840
                            {
3841
                                string joinModelItemId = modelItemIds[0];
3842
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
3843
                                if (survivorId != null)
3844
                                    break;
3845
                            }
3846
                        }
3847
                    }
3848
                }
3849
            }
3850
        }
3851

    
3852
        /// <summary>
3853
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
3854
        /// </summary>
3855
        /// <param name="x"></param>
3856
        /// <param name="y"></param>
3857
        /// <param name="originX"></param>
3858
        /// <param name="originY"></param>
3859
        /// <param name="SPPIDLabelLocation"></param>
3860
        /// <param name="location"></param>
3861
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
3862
        {
3863
            if (location == Location.None)
3864
            {
3865
                x = originX;
3866
                y = originY;
3867
            }
3868
            else
3869
            {
3870
                if (location.HasFlag(Location.Center))
3871
                {
3872
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
3873
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
3874
                }
3875

    
3876
                if (location.HasFlag(Location.Left))
3877
                    x = SPPIDLabelLocation.X1;
3878
                else if (location.HasFlag(Location.Right))
3879
                    x = SPPIDLabelLocation.X2;
3880

    
3881
                if (location.HasFlag(Location.Down))
3882
                    y = SPPIDLabelLocation.Y1;
3883
                else if (location.HasFlag(Location.Up))
3884
                    y = SPPIDLabelLocation.Y2;
3885
            }
3886
        }
3887

    
3888
        /// <summary>
3889
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
3890
        /// 1. Angle Valve
3891
        /// 2. 3개로 이루어진 Symbol Group
3892
        /// </summary>
3893
        /// <returns></returns>
3894
        private List<Symbol> GetPrioritySymbol()
3895
        {
3896
            DataTable symbolTable = document.SymbolTable;
3897
            // List에 순서대로 쌓는다.
3898
            List<Symbol> symbols = new List<Symbol>();
3899

    
3900
            // Angle Valve 부터
3901
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
3902
            {
3903
                if (!symbols.Contains(symbol))
3904
                {
3905
                    double originX = 0;
3906
                    double originY = 0;
3907

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

    
3912
                    SlopeType slopeType1 = SlopeType.None;
3913
                    SlopeType slopeType2 = SlopeType.None;
3914
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
3915
                    {
3916
                        double connectorX = 0;
3917
                        double connectorY = 0;
3918
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
3919
                        if (slopeType1 == SlopeType.None)
3920
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3921
                        else
3922
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
3923
                    }
3924

    
3925
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
3926
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
3927
                        symbols.Add(symbol);
3928
                }
3929
            }
3930

    
3931
            List<Symbol> tempSymbols = new List<Symbol>();
3932
            // Conn 갯수 기준
3933
            foreach (var item in document.SYMBOLS)
3934
            {
3935
                if (!symbols.Contains(item))
3936
                    tempSymbols.Add(item);
3937
            }
3938
            tempSymbols.Sort(SortSymbolPriority);
3939
            symbols.AddRange(tempSymbols);
3940

    
3941
            return symbols;
3942
        }
3943

    
3944
        private void SetPriorityLine(List<Line> lines)
3945
        {
3946
            lines.Sort(SortLinePriority);
3947

    
3948
            int SortLinePriority(Line a, Line b)
3949
            {
3950
                // Branch 없는것부터
3951
                int branchRetval = CompareBranchLine(a, b);
3952
                if (branchRetval != 0)
3953
                {
3954
                    return branchRetval;
3955
                }
3956
                else
3957
                {
3958
                    // Symbol 연결 갯수
3959
                    int connSymbolRetval = CompareConnSymbol(a, b);
3960
                    if (connSymbolRetval != 0)
3961
                    {
3962
                        return connSymbolRetval;
3963
                    }
3964
                    else
3965
                    {
3966
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
3967
                        int connItemRetval = CompareConnItem(a, b);
3968
                        if (connItemRetval != 0)
3969
                        {
3970
                            return connItemRetval;
3971
                        }
3972
                        else
3973
                        {
3974
                            // ConnectedItem이 없는것
3975
                            int noneConnRetval = CompareNoneConn(a, b);
3976
                            if (noneConnRetval != 0)
3977
                            {
3978
                                return noneConnRetval;
3979
                            }
3980
                            else
3981
                            {
3982

    
3983
                            }
3984
                        }
3985
                    }
3986
                }
3987

    
3988
                return 0;
3989
            }
3990

    
3991
            int CompareNotSegmentLine(Line a, Line b)
3992
            {
3993
                List<Connector> connectorsA = a.CONNECTORS
3994
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3995
                    .ToList();
3996

    
3997
                List<Connector> connectorsB = b.CONNECTORS
3998
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3999
                    .ToList();
4000

    
4001
                // 오름차순
4002
                return connectorsB.Count.CompareTo(connectorsA.Count);
4003
            }
4004

    
4005
            int CompareConnSymbol(Line a, Line b)
4006
            {
4007
                List<Connector> connectorsA = a.CONNECTORS
4008
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4009
                    .ToList();
4010

    
4011
                List<Connector> connectorsB = b.CONNECTORS
4012
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4013
                    .ToList();
4014

    
4015
                // 오름차순
4016
                return connectorsB.Count.CompareTo(connectorsA.Count);
4017
            }
4018

    
4019
            int CompareConnItem(Line a, Line b)
4020
            {
4021
                List<Connector> connectorsA = a.CONNECTORS
4022
                    .Where(conn => conn.ConnectedObject != null && 
4023
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
4024
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
4025
                    .ToList();
4026

    
4027
                List<Connector> connectorsB = b.CONNECTORS
4028
                    .Where(conn => conn.ConnectedObject != null &&
4029
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
4030
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
4031
                    .ToList();
4032

    
4033
                // 오름차순
4034
                return connectorsB.Count.CompareTo(connectorsA.Count);
4035
            }
4036

    
4037
            int CompareBranchLine(Line a, Line b)
4038
            {
4039
                List<Connector> connectorsA = a.CONNECTORS
4040
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
4041
                    .ToList();
4042
                List<Connector> connectorsB = b.CONNECTORS
4043
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
4044
                    .ToList();
4045

    
4046
                // 내림차순
4047
                return connectorsA.Count.CompareTo(connectorsB.Count);
4048
            }
4049

    
4050
            int CompareNoneConn(Line a, Line b)
4051
            {
4052
                List<Connector> connectorsA = a.CONNECTORS
4053
                    .Where(conn => conn.ConnectedObject == null)
4054
                    .ToList();
4055

    
4056
                List<Connector> connectorsB = b.CONNECTORS
4057
                    .Where(conn => conn.ConnectedObject == null)
4058
                    .ToList();
4059

    
4060
                // 오름차순
4061
                return connectorsB.Count.CompareTo(connectorsA.Count);
4062
            }
4063
        }
4064

    
4065
        private void SortBranchLines()
4066
        {
4067
            BranchLines.Sort(SortBranchLine);
4068
            int SortBranchLine(Line a, Line b)
4069
            {
4070
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4071
                 x.ConnectedObject.GetType() == typeof(Line) &&
4072
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
4073
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4074

    
4075
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4076
                 x.ConnectedObject.GetType() == typeof(Line) &&
4077
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
4078
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4079

    
4080
                // 내림차순
4081
                return countA.CompareTo(countB);
4082
            }
4083
        }
4084

    
4085
        private static int SortSymbolPriority(Symbol a, Symbol b)
4086
        {
4087
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4088
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4089
            int retval = countB.CompareTo(countA);
4090
            if (retval != 0)
4091
                return retval;
4092
            else
4093
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
4094
        }
4095

    
4096
        private string GetSPPIDFileName(LMModelItem modelItem)
4097
        {
4098
            string symbolPath = null;
4099
            foreach (LMRepresentation rep in modelItem.Representations)
4100
            {
4101
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4102
                {
4103
                    symbolPath = rep.get_FileName();
4104
                    break;
4105
                }
4106
            }
4107
            return symbolPath;
4108
        }
4109

    
4110
        private string GetSPPIDFileName(string modelItemId)
4111
        {
4112
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4113
            string symbolPath = null;
4114
            foreach (LMRepresentation rep in modelItem.Representations)
4115
            {
4116
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4117
                {
4118
                    symbolPath = rep.get_FileName();
4119
                    break;
4120
                }
4121
            }
4122
            ReleaseCOMObjects(modelItem);
4123
            return symbolPath;
4124
        }
4125

    
4126
        /// <summary>
4127
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
4128
        /// </summary>
4129
        /// <param name="graphicOID"></param>
4130
        /// <param name="milliseconds"></param>
4131
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
4132
        {
4133
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
4134
            {
4135
                double minX = 0;
4136
                double minY = 0;
4137
                double maxX = 0;
4138
                double maxY = 0;
4139
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
4140
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
4141

    
4142
                Thread.Sleep(milliseconds);
4143
            }
4144
        }
4145

    
4146
        /// <summary>
4147
        /// ComObject를 Release
4148
        /// </summary>
4149
        /// <param name="objVars"></param>
4150
        public void ReleaseCOMObjects(params object[] objVars)
4151
        {
4152
            if (objVars != null)
4153
            {
4154
                int intNewRefCount = 0;
4155
                foreach (object obj in objVars)
4156
                {
4157
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
4158
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
4159
                }
4160
            }
4161
        }
4162

    
4163
        /// IDisposable 구현
4164
        ~AutoModeling()
4165
        {
4166
            this.Dispose(false);
4167
        }
4168

    
4169
        private bool disposed;
4170
        public void Dispose()
4171
        {
4172
            this.Dispose(true);
4173
            GC.SuppressFinalize(this);
4174
        }
4175

    
4176
        protected virtual void Dispose(bool disposing)
4177
        {
4178
            if (this.disposed) return;
4179
            if (disposing)
4180
            {
4181
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
4182
            }
4183
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
4184
            this.disposed = true;
4185
        }
4186
    }
4187
}
클립보드 이미지 추가 (최대 크기: 500 MB)