프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 1299077b

이력 | 보기 | 이력해설 | 다운로드 (207 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, 20);
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
                    // Join Run
109
                    RunJoinRun();
110
                    // Check FlowDirection
111
                    RunFlowDirection();
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.InsertDrawingInfoAndOPCInfo(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
                        modelItem = null;
519
                    }
520
                }
521

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

    
534
                SetFlowDirectionByLine(modelId);
535

    
536
                ReleaseCOMObjects(zeroLengthModelItem);
537
                zeroLengthModelItem = null;
538

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

    
551
                SetFlowDirectionByLine(modelId);
552

    
553
                ReleaseCOMObjects(zeroLengthModelItem);
554
                zeroLengthModelItem = null;
555

    
556
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
557
            }
558
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
559
            {
560
                SetFlowDirectionByLine(modelId);
561
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
562
            }
563

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

    
579
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
580
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
581
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
582
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
583

    
584
                                ReleaseCOMObjects(connector);
585
                            }
586
                        }
587
                    }
588
                    ReleaseCOMObjects(modelItem);
589
                    modelItem = null;
590
                }
591

    
592
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
593
                {
594
                    // Item2가 Symbol
595
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
596
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
597
                    {
598
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
599
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
600
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
601

    
602
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
603

    
604
                        symbolModelItem.Commit();
605
                        ReleaseCOMObjects(symbolModelItem);
606
                        symbolModelItem = null;
607
                    }
608
                    // Item1이 Symbol
609
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
610
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
611
                    {
612
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
613
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
614
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
615

    
616
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
617

    
618
                        symbolModelItem.Commit();
619
                        ReleaseCOMObjects(symbolModelItem);
620
                        symbolModelItem = null;
621
                    }
622
                }
623

    
624
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
625
                {
626
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
627
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
628
                    if (attribute != null)
629
                    {
630
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
631
                            attribute.set_Value("End 1 is downstream (Outlet)");
632
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
633
                            attribute.set_Value("End 1 is upstream (Inlet)");
634
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
635
                            attribute.set_Value("End 1 is upstream (Inlet)");
636
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
637
                            attribute.set_Value("End 1 is downstream (Outlet)");
638
                    }
639
                }
640
            }
641
        }
642
        private void RunNoteModeling()
643
        {
644
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
645
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
646
            List<Note> correctList = new List<Note>();
647
            foreach (var item in document.NOTES)
648
                try
649
                {
650
                    NoteModeling(item, correctList);
651
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
652
                }
653
                catch (Exception ex)
654
                {
655
                    Log.Write("Error in NoteModeling");
656
                    Log.Write("UID : " + item.UID);
657
                    Log.Write(ex.Message);
658
                    Log.Write(ex.StackTrace);
659
                }
660

    
661
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
662
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
663
            SortNote(correctList);
664
            List<Note> endList = new List<Note>();
665
            if (correctList.Count > 0)
666
                endList.Add(correctList[0]);
667
            foreach (var item in document.NOTES)
668
                try
669
                {
670
                    if (!endList.Contains(item))
671
                        NoteCorrectModeling(item, endList);
672
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
673
                }
674
                catch (Exception ex)
675
                {
676
                    Log.Write("Error in NoteModeling");
677
                    Log.Write("UID : " + item.UID);
678
                    Log.Write(ex.Message);
679
                    Log.Write(ex.StackTrace);
680
                }
681
        }
682
        private void RunTextModeling()
683
        {
684
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
685
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
686
            List<Text> correctList = new List<Text>();
687
            foreach (var item in document.TEXTINFOS)
688
                try
689
                {
690
                    TextModeling(item, correctList);
691
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
692
                }
693
                catch (Exception ex)
694
                {
695
                    Log.Write("Error in TextModeling");
696
                    Log.Write("UID : " + item.UID);
697
                    Log.Write(ex.Message);
698
                    Log.Write(ex.StackTrace);
699
                }
700

    
701
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
702
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Text");
703
            SortText(correctList);
704
            List<Text> endList = new List<Text>();
705
            if (correctList.Count > 0)
706
                endList.Add(correctList[0]);
707
            foreach (var item in correctList)
708
                try
709
                {
710
                    if (!endList.Contains(item))
711
                        TextCorrectModeling(item, endList);
712
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
713
                }
714
                catch (Exception ex)
715
                {
716
                    Log.Write("Error in TextModeling");
717
                    Log.Write("UID : " + item.UID);
718
                    Log.Write(ex.Message);
719
                    Log.Write(ex.StackTrace);
720
                }
721
        }
722
        private void RunInputLineNumberAttribute()
723
        {
724
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
725
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
726
            List<string> endLine = new List<string>();
727
            foreach (var item in document.LINENUMBERS)
728
                try
729
                {
730
                    InputLineNumberAttribute(item, endLine);
731
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
732
                }
733
                catch (Exception ex)
734
                {
735
                    Log.Write("Error in InputLineNumberAttribute");
736
                    Log.Write("UID : " + item.UID);
737
                    Log.Write(ex.Message);
738
                    Log.Write(ex.StackTrace);
739
                }
740
        }
741
        private void RunInputSymbolAttribute()
742
        {
743
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
744
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
745
            foreach (var item in document.SYMBOLS)
746
                try
747
                {
748
                    InputSymbolAttribute(item, item.ATTRIBUTES);
749
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
750
                }
751
                catch (Exception ex)
752
                {
753
                    Log.Write("Error in InputSymbolAttribute");
754
                    Log.Write("UID : " + item.UID);
755
                    Log.Write(ex.Message);
756
                    Log.Write(ex.StackTrace);
757
                }
758
        }
759
        private void RunInputSpecBreakAttribute()
760
        {
761
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
762
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
763
            foreach (var item in document.SpecBreaks)
764
                try
765
                {
766
                    InputSpecBreakAttribute(item);
767
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
768
                }
769
                catch (Exception ex)
770
                {
771
                    Log.Write("Error in InputSpecBreakAttribute");
772
                    Log.Write("UID : " + item.UID);
773
                    Log.Write(ex.Message);
774
                    Log.Write(ex.StackTrace);
775
                }
776
        }
777
        private void RunLabelSymbolModeling()
778
        {
779
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
780
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
781
            foreach (var item in document.SYMBOLS)
782
                try
783
                {
784
                    LabelSymbolModeling(item);
785
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
786
                }
787
                catch (Exception ex)
788
                {
789
                    Log.Write("Error in LabelSymbolModeling");
790
                    Log.Write("UID : " + item.UID);
791
                    Log.Write(ex.Message);
792
                    Log.Write(ex.StackTrace);
793
                }
794
        }
795
        
796
        /// <summary>
797
        /// 도면 생성 메서드
798
        /// </summary>
799
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
800
        {
801
            Log.Write("------------------ Start create document ------------------");
802
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
803
            Log.Write("Drawing name : " + drawingName);
804
            Log.Write("Drawing number : " + drawingNumber);
805
            Thread.Sleep(1000);
806
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
807
            if (newDrawing != null)
808
            {
809
                document.SPPID_DrawingNumber = drawingNumber;
810
                document.SPPID_DrawingName = drawingName;
811
                Thread.Sleep(1000);
812
                radApp.ActiveWindow.Fit();
813
                Thread.Sleep(1000);
814
                radApp.ActiveWindow.Zoom = 2000;
815
                Thread.Sleep(2000);
816

    
817
                //current LMDrawing 가져오기
818
                LMAFilter filter = new LMAFilter();
819
                LMACriterion criterion = new LMACriterion();
820
                filter.ItemType = "Drawing";
821
                criterion.SourceAttributeName = "Name";
822
                criterion.Operator = "=";
823
                criterion.set_ValueAttribute(drawingName);
824
                filter.get_Criteria().Add(criterion);
825

    
826
                LMDrawings drawings = new LMDrawings();
827
                drawings.Collect(dataSource, Filter: filter);
828

    
829
                drawingID = ((dynamic)drawings).Nth(1).Id;
830
                ReleaseCOMObjects(filter);
831
                ReleaseCOMObjects(criterion);
832
                ReleaseCOMObjects(drawings);
833
                filter = null;
834
                criterion = null;
835
                drawings = null;
836
            }
837
            else
838
                Log.Write("Fail Create Drawing");
839

    
840
            if (newDrawing != null)
841
                return true;
842
            else
843
                return false;
844
        }
845

    
846
        /// <summary>
847
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
848
        /// </summary>
849
        /// <param name="drawingName"></param>
850
        /// <param name="drawingNumber"></param>
851
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
852
        {
853
            LMDrawings drawings = new LMDrawings();
854
            drawings.Collect(dataSource);
855

    
856
            List<string> drawingNameList = new List<string>();
857
            List<string> drawingNumberList = new List<string>();
858

    
859
            foreach (LMDrawing item in drawings)
860
            {
861
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
862
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
863
            }
864

    
865
            int nameLength = drawingName.Length;
866
            while (drawingNameList.Contains(drawingName))
867
            {
868
                if (nameLength == drawingName.Length)
869
                    drawingName += "-1";
870
                else
871
                {
872
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
873
                    drawingName = drawingName.Substring(0, nameLength + 1);
874
                    drawingName += ++index;
875
                }
876
            }
877

    
878
            int numberLength = drawingNumber.Length;
879
            while (drawingNameList.Contains(drawingNumber))
880
            {
881
                if (numberLength == drawingNumber.Length)
882
                    drawingNumber += "-1";
883
                else
884
                {
885
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
886
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
887
                    drawingNumber += ++index;
888
                }
889
            }
890
            ReleaseCOMObjects(drawings);
891
            drawings = null;
892
        }
893

    
894
        /// <summary>
895
        /// 도면 크기 구하는 메서드
896
        /// </summary>
897
        /// <returns></returns>
898
        private bool DocumentCoordinateCorrection()
899
        {
900
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
901
            {
902
                Log.Write("Setting Drawing X, Drawing Y");
903
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
904
                Log.Write("Start coordinate correction");
905
                document.CoordinateCorrection();
906
                return true;
907
            }
908
            else
909
            {
910
                Log.Write("Need Drawing X, Y");
911
                return false;
912
            }
913
        }
914

    
915
        /// <summary>
916
        /// 심볼을 실제로 Modeling 메서드
917
        /// </summary>
918
        /// <param name="symbol">생성할 심볼</param>
919
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
920
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
921
        {
922
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
923
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
924
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
925
                return;
926
            // 이미 모델링 됐을 경우
927
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
928
                return;
929

    
930
            LMSymbol _LMSymbol = null;
931

    
932
            string mappingPath = symbol.SPPID.MAPPINGNAME;
933
            double x = symbol.SPPID.ORIGINAL_X;
934
            double y = symbol.SPPID.ORIGINAL_Y;
935
            int mirror = 0;
936
            double angle = symbol.ANGLE;
937

    
938
            // OPC 일경우 180도 일때 Mirror
939
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
940
                mirror = 1;
941

    
942
            // Mirror 계산
943
            if (symbol.FLIP == 1)
944
            {
945
                mirror = 1;
946
                angle += Math.PI;
947
            }
948

    
949
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
950
            {
951
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
952
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
953
                if (connector != null)
954
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
955

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

    
958
                if (_LMSymbol != null && _TargetItem != null)
959
                {
960
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
961

    
962
                    if (SPPIDUtil.IsSegmentLine(document, symbol, targetSymbol))
963
                    {
964
                        LMConnector reModelingConnector = FindBreakLineTarget(symbol, targetSymbol);
965
                        if (reModelingConnector != null)
966
                            ReModelingLMConnector(reModelingConnector);
967
                    }
968
                }
969

    
970
                ReleaseCOMObjects(_TargetItem);
971
            }
972
            else
973
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
974

    
975
            if (_LMSymbol != null)
976
            {
977
                _LMSymbol.Commit();
978

    
979
                // ConnCheck
980
                List<string> ids = new List<string>();
981
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
982
                {
983
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
984
                        ids.Add(item.Id);
985
                    ReleaseCOMObjects(item);
986
                }
987
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
988
                {
989
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
990
                        ids.Add(item.Id);
991
                    ReleaseCOMObjects(item);
992
                }
993

    
994
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
995
                if (targetSymbol == null && ids.Count != createdSymbolCount)
996
                {
997
                    double currentX = _LMSymbol.get_XCoordinate();
998
                    double currentY = _LMSymbol.get_YCoordinate();
999

    
1000

    
1001
                }
1002

    
1003
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1004
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1005
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1006

    
1007
                foreach (var item in symbol.ChildSymbols)
1008
                    CreateChildSymbol(item, _LMSymbol, symbol);
1009

    
1010
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1011
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1012

    
1013
                double[] range = null;
1014
                GetSPPIDSymbolRange(symbol, ref range);
1015
                symbol.SPPID.SPPID_Min_X = range[0];
1016
                symbol.SPPID.SPPID_Min_Y = range[1];
1017
                symbol.SPPID.SPPID_Max_X = range[2];
1018
                symbol.SPPID.SPPID_Max_Y = range[3];
1019

    
1020
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1021
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1022
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1023
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1024

    
1025
                ReleaseCOMObjects(_LMSymbol);
1026
            }
1027
        }
1028

    
1029
        private void RemoveSymbol(Symbol symbol)
1030
        {
1031
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1032
            {
1033
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1034
                if (_LMSymbol != null)
1035
                {
1036
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1037
                    ReleaseCOMObjects(_LMSymbol);
1038
                }
1039
            }
1040

    
1041
            symbol.SPPID.RepresentationId = string.Empty;
1042
            symbol.SPPID.ModelItemID = string.Empty;
1043
            symbol.SPPID.SPPID_X = double.NaN;
1044
            symbol.SPPID.SPPID_Y = double.NaN;
1045
            symbol.SPPID.SPPID_Min_X = double.NaN;
1046
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1047
            symbol.SPPID.SPPID_Max_X = double.NaN;
1048
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1049
        }
1050

    
1051
        private void RemoveSymbol(List<Symbol> symbols)
1052
        {
1053
            foreach (var symbol in symbols)
1054
            {
1055
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1056
                {
1057
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1058
                    if (_LMSymbol != null)
1059
                    {
1060
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1061
                        ReleaseCOMObjects(_LMSymbol);
1062
                    }
1063
                }
1064

    
1065
                symbol.SPPID.RepresentationId = string.Empty;
1066
                symbol.SPPID.ModelItemID = string.Empty;
1067
                symbol.SPPID.SPPID_X = double.NaN;
1068
                symbol.SPPID.SPPID_Y = double.NaN;
1069
                symbol.SPPID.SPPID_Min_X = double.NaN;
1070
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1071
                symbol.SPPID.SPPID_Max_X = double.NaN;
1072
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1073
            }
1074
        }
1075

    
1076
        /// <summary>
1077
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1078
        /// </summary>
1079
        /// <param name="targetConnector"></param>
1080
        /// <param name="targetSymbol"></param>
1081
        /// <param name="x"></param>
1082
        /// <param name="y"></param>
1083
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1084
        {
1085
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1086

    
1087
            double[] range = null;
1088
            List<double[]> points = new List<double[]>();
1089
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1090
            double x1 = range[0];
1091
            double y1 = range[1];
1092
            double x2 = range[2];
1093
            double y2 = range[3];
1094

    
1095
            // Origin 기준 Connector의 위치차이
1096
            double sceneX = 0;
1097
            double sceneY = 0;
1098
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1099
            double originX = 0;
1100
            double originY = 0;
1101
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1102
            double gapX = originX - sceneX;
1103
            double gapY = originY - sceneY;
1104

    
1105
            // SPPID Symbol과 ID2 심볼의 크기 차이
1106
            double sizeWidth = 0;
1107
            double sizeHeight = 0;
1108
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1109
            if (sizeWidth == 0 || sizeHeight == 0)
1110
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1111

    
1112
            double percentX = (x2 - x1) / sizeWidth;
1113
            double percentY = (y2 - y1) / sizeHeight;
1114

    
1115
            double SPPIDgapX = gapX * percentX;
1116
            double SPPIDgapY = gapY * percentY;
1117

    
1118
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1119
            double distance = double.MaxValue;
1120
            double[] resultPoint;
1121
            foreach (var point in points)
1122
            {
1123
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1124
                if (distance > result)
1125
                {
1126
                    distance = result;
1127
                    resultPoint = point;
1128
                    x = point[0];
1129
                    y = point[1];
1130
                }
1131
            }
1132

    
1133
            ReleaseCOMObjects(_TargetItem);
1134
        }
1135

    
1136
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1137
        {
1138
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1139
            if (index == 0)
1140
            {
1141
                x = targetLine.SPPID.START_X;
1142
                y = targetLine.SPPID.START_Y;
1143
            }
1144
            else
1145
            {
1146
                x = targetLine.SPPID.END_X;
1147
                y = targetLine.SPPID.END_Y;
1148
            }
1149
        }
1150

    
1151
        /// <summary>
1152
        /// SPPID Symbol의 Range를 구한다.
1153
        /// </summary>
1154
        /// <param name="symbol"></param>
1155
        /// <param name="range"></param>
1156
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1157
        {
1158
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1159
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1160
            double x1 = 0;
1161
            double y1 = 0;
1162
            double x2 = 0;
1163
            double y2 = 0;
1164
            symbol2d.Range(out x1, out y1, out x2, out y2);
1165
            range = new double[] { x1, y1, x2, y2 };
1166

    
1167
            for (int i = 1; i < int.MaxValue; i++)
1168
            {
1169
                double connX = 0;
1170
                double connY = 0;
1171
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1172
                    points.Add(new double[] { connX, connY });
1173
                else
1174
                    break;
1175
            }
1176

    
1177
            foreach (var childSymbol in symbol.ChildSymbols)
1178
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1179

    
1180
            ReleaseCOMObjects(_TargetItem);
1181
        }
1182

    
1183
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range)
1184
        {
1185
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1186
            if (_TargetItem != null)
1187
            {
1188
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1189
                double x1 = 0;
1190
                double y1 = 0;
1191
                double x2 = 0;
1192
                double y2 = 0;
1193
                symbol2d.Range(out x1, out y1, out x2, out y2);
1194
                range = new double[] { x1, y1, x2, y2 };
1195

    
1196
                foreach (var childSymbol in symbol.ChildSymbols)
1197
                    GetSPPIDChildSymbolRange(childSymbol, ref range);
1198

    
1199
                ReleaseCOMObjects(_TargetItem);
1200
            }
1201
        }
1202

    
1203
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1204
        {
1205
            if (labelPersist != null)
1206
            {
1207
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1208
                if (dependency != null)
1209
                {
1210
                    double x1 = 0;
1211
                    double y1 = 0;
1212
                    double x2 = 0;
1213
                    double y2 = 0;
1214
                    dependency.Range(out x1, out y1, out x2, out y2);
1215
                    range = new double[] { x1, y1, x2, y2 };
1216
                }
1217
            }
1218
        }
1219

    
1220
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1221
        {
1222
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1223
            foreach (var symbol in symbols)
1224
            {
1225
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1226
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1227
                double x1 = 0;
1228
                double y1 = 0;
1229
                double x2 = 0;
1230
                double y2 = 0;
1231
                symbol2d.Range(out x1, out y1, out x2, out y2);
1232

    
1233
                tempRange[0] = Math.Min(tempRange[0], x1);
1234
                tempRange[1] = Math.Min(tempRange[1], y1);
1235
                tempRange[2] = Math.Max(tempRange[2], x2);
1236
                tempRange[3] = Math.Max(tempRange[3], y2);
1237

    
1238
                foreach (var childSymbol in symbol.ChildSymbols)
1239
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1240

    
1241
                ReleaseCOMObjects(_TargetItem);
1242
            }
1243

    
1244
            range = tempRange;
1245
        }
1246

    
1247
        /// <summary>
1248
        /// Child Modeling 된 Symbol의 Range를 구한다.
1249
        /// </summary>
1250
        /// <param name="childSymbol"></param>
1251
        /// <param name="range"></param>
1252
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1253
        {
1254
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1255
            if (_ChildSymbol != null)
1256
            {
1257
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1258
                double x1 = 0;
1259
                double y1 = 0;
1260
                double x2 = 0;
1261
                double y2 = 0;
1262
                symbol2d.Range(out x1, out y1, out x2, out y2);
1263
                range[0] = Math.Min(range[0], x1);
1264
                range[1] = Math.Min(range[1], y1);
1265
                range[2] = Math.Max(range[2], x2);
1266
                range[3] = Math.Max(range[3], y2);
1267

    
1268
                for (int i = 1; i < int.MaxValue; i++)
1269
                {
1270
                    double connX = 0;
1271
                    double connY = 0;
1272
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1273
                        points.Add(new double[] { connX, connY });
1274
                    else
1275
                        break;
1276
                }
1277

    
1278
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1279
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1280

    
1281
                ReleaseCOMObjects(_ChildSymbol);
1282
            }
1283
        }
1284

    
1285
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1286
        {
1287
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1288
            if (_ChildSymbol != null)
1289
            {
1290
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1291
                double x1 = 0;
1292
                double y1 = 0;
1293
                double x2 = 0;
1294
                double y2 = 0;
1295
                symbol2d.Range(out x1, out y1, out x2, out y2);
1296
                range[0] = Math.Min(range[0], x1);
1297
                range[1] = Math.Min(range[1], y1);
1298
                range[2] = Math.Max(range[2], x2);
1299
                range[3] = Math.Max(range[3], y2);
1300

    
1301
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1302
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1303
                ReleaseCOMObjects(_ChildSymbol);
1304
            }
1305
        }
1306

    
1307
        /// <summary>
1308
        /// Label Symbol Modeling
1309
        /// </summary>
1310
        /// <param name="symbol"></param>
1311
        private void LabelSymbolModeling(Symbol symbol)
1312
        {
1313
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1314
            {
1315
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1316
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1317
                    return;
1318
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1319

    
1320
                string symbolUID = itemAttribute.VALUE;
1321
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1322
                if (targetItem != null &&
1323
                    (targetItem.GetType() == typeof(Symbol) ||
1324
                    targetItem.GetType() == typeof(Equipment)))
1325
                {
1326
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1327
                    string sRep = null;
1328
                    if (targetItem.GetType() == typeof(Symbol))
1329
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1330
                    else if (targetItem.GetType() == typeof(Equipment))
1331
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1332
                    if (!string.IsNullOrEmpty(sRep))
1333
                    {
1334
                        // LEADER Line 검사
1335
                        bool leaderLine = false;
1336
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1337
                        if (symbolMapping != null)
1338
                            leaderLine = symbolMapping.LEADERLINE;
1339

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

    
1344
                        //Leader 선 센터로
1345
                        if (_LMLabelPresist != null)
1346
                        {
1347
                            // Target Item에 Label의 Attribute Input
1348
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1349

    
1350
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1351
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1352
                            if (dependency != null)
1353
                            {
1354
                                bool result = false;
1355
                                foreach (var attributes in dependency.AttributeSets)
1356
                                {
1357
                                    foreach (var attribute in attributes)
1358
                                    {
1359
                                        string name = attribute.Name;
1360
                                        string value = attribute.GetValue().ToString();
1361
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1362
                                        {
1363
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1364
                                            {
1365
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1366
                                                {
1367
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1368
                                                    double prevX = _TargetItem.get_XCoordinate();
1369
                                                    double prevY = _TargetItem.get_YCoordinate();
1370
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1371
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1372
                                                    result = true;
1373
                                                    break;
1374
                                                }
1375
                                            }
1376
                                        }
1377

    
1378
                                        if (result)
1379
                                            break;
1380
                                    }
1381

    
1382
                                    if (result)
1383
                                        break;
1384
                                }
1385
                            }
1386

    
1387
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1388
                            _LMLabelPresist.Commit();
1389
                            ReleaseCOMObjects(_LMLabelPresist);
1390
                        }
1391

    
1392
                        ReleaseCOMObjects(_TargetItem);
1393
                    }
1394
                }
1395
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1396
                {
1397
                    Line targetLine = targetItem as Line;
1398
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1399
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1400
                    if (connectedLMConnector != null)
1401
                    {
1402
                        // LEADER Line 검사
1403
                        bool leaderLine = false;
1404
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1405
                        if (symbolMapping != null)
1406
                            leaderLine = symbolMapping.LEADERLINE;
1407

    
1408
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1409
                        if (_LMLabelPresist != null)
1410
                        {
1411
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1412
                            _LMLabelPresist.Commit();
1413
                            ReleaseCOMObjects(_LMLabelPresist);
1414
                        }
1415
                        ReleaseCOMObjects(connectedLMConnector);
1416
                    }
1417

    
1418
                    foreach (var item in connectorVertices)
1419
                        if (item.Key != null)
1420
                            ReleaseCOMObjects(item.Key);
1421
                }
1422
            }
1423
        }
1424

    
1425
        /// <summary>
1426
        /// Equipment를 실제로 Modeling 메서드
1427
        /// </summary>
1428
        /// <param name="equipment"></param>
1429
        private void EquipmentModeling(Equipment equipment)
1430
        {
1431
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1432
                return;
1433

    
1434
            LMSymbol _LMSymbol = null;
1435
            LMSymbol targetItem = null;
1436
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1437
            double x = equipment.SPPID.ORIGINAL_X;
1438
            double y = equipment.SPPID.ORIGINAL_Y;
1439
            int mirror = 0;
1440
            double angle = equipment.ANGLE;
1441

    
1442
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1443

    
1444
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1445
            if (connector != null)
1446
            {
1447
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1448
                if (connEquipment != null)
1449
                {
1450
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1451
                        EquipmentModeling(connEquipment);
1452

    
1453
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1454
                    {
1455
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1456
                        if (targetItem != null)
1457
                        {
1458
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1459
                        }
1460
                        else
1461
                        {
1462
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1463
                        }
1464
                    }
1465
                    else
1466
                    {
1467
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1468
                    }
1469
                }
1470
                else
1471
                {
1472
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1473
                }
1474
            }
1475
            else
1476
            {
1477
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1478
            }
1479

    
1480
            if (_LMSymbol != null)
1481
            {
1482
                _LMSymbol.Commit();
1483
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1484
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1485
                ReleaseCOMObjects(_LMSymbol);
1486
            }
1487

    
1488
            if (targetItem != null)
1489
            {
1490
                ReleaseCOMObjects(targetItem);
1491
            }
1492

    
1493
            ReleaseCOMObjects(_LMSymbol);
1494
        }
1495

    
1496
        /// <summary>
1497
        /// 첫 진입점
1498
        /// </summary>
1499
        /// <param name="symbol"></param>
1500
        private void SymbolModelingBySymbol(Symbol symbol)
1501
        {
1502
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1503
            List<object> endObjects = new List<object>();
1504
            endObjects.Add(symbol);
1505

    
1506
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1507
            foreach (var connector in symbol.CONNECTORS)
1508
            {
1509
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1510
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1511
                {
1512
                    endObjects.Add(connItem);
1513
                    if (connItem.GetType() == typeof(Symbol))
1514
                    {
1515
                        Symbol connSymbol = connItem as Symbol;
1516
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1517
                        {
1518
                            SymbolModeling(connSymbol, symbol);
1519
                        }
1520
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1521
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1522
                    }
1523
                    else if (connItem.GetType() == typeof(Line))
1524
                    {
1525
                        Line connLine = connItem as Line;
1526
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1527
                    }
1528
                }
1529
            }
1530
        }
1531

    
1532
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1533
        {
1534
            foreach (var connector in symbol.CONNECTORS)
1535
            {
1536
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1537
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1538
                {
1539
                    if (!endObjects.Contains(connItem))
1540
                    {
1541
                        endObjects.Add(connItem);
1542
                        if (connItem.GetType() == typeof(Symbol))
1543
                        {
1544
                            Symbol connSymbol = connItem as Symbol;
1545
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1546
                            {
1547
                                SymbolModeling(connSymbol, symbol);
1548
                            }
1549
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1550
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1551
                        }
1552
                        else if (connItem.GetType() == typeof(Line))
1553
                        {
1554
                            Line connLine = connItem as Line;
1555
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1556
                        }
1557
                    }
1558
                }
1559
            }
1560
        }
1561

    
1562
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1563
        {
1564
            foreach (var connector in line.CONNECTORS)
1565
            {
1566
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1567
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1568
                {
1569
                    if (!endObjects.Contains(connItem))
1570
                    {
1571
                        endObjects.Add(connItem);
1572
                        if (connItem.GetType() == typeof(Symbol))
1573
                        {
1574
                            Symbol connSymbol = connItem as Symbol;
1575
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1576
                            {
1577
                                List<Symbol> group = new List<Symbol>();
1578
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1579
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1580
                                List<Symbol> endModelingGroup = new List<Symbol>();
1581
                                if (priority != null)
1582
                                {
1583
                                    SymbolGroupModeling(priority, group);
1584

    
1585
                                    // Range 겹치는지 확인해야함
1586
                                    double[] prevRange = null;
1587
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1588
                                    double[] groupRange = null;
1589
                                    GetSPPIDSymbolRange(group, ref groupRange);
1590

    
1591
                                    double distanceX = 0;
1592
                                    double distanceY = 0;
1593
                                    bool overlapX = false;
1594
                                    bool overlapY = false;
1595
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1596
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1597
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1598
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1599
                                    {
1600
                                        RemoveSymbol(group);
1601
                                        foreach (var _temp in group)
1602
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1603

    
1604
                                        SymbolGroupModeling(priority, group);
1605
                                    }
1606
                                }
1607
                                else
1608
                                {
1609
                                    SymbolModeling(connSymbol, null);
1610
                                    // Range 겹치는지 확인해야함
1611
                                    double[] prevRange = null;
1612
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1613
                                    double[] connRange = null;
1614
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1615

    
1616
                                    double distanceX = 0;
1617
                                    double distanceY = 0;
1618
                                    bool overlapX = false;
1619
                                    bool overlapY = false;
1620
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1621
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1622
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1623
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1624
                                    {
1625
                                        RemoveSymbol(connSymbol);
1626
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1627

    
1628
                                        SymbolModeling(connSymbol, null);
1629
                                    }
1630
                                }
1631
                            }
1632
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1633
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1634
                        }
1635
                        else if (connItem.GetType() == typeof(Line))
1636
                        {
1637
                            Line connLine = connItem as Line;
1638
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1639
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1640
                        }
1641
                    }
1642
                }
1643
            }
1644
        }
1645

    
1646
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1647
        {
1648
            List<Symbol> endModelingGroup = new List<Symbol>();
1649
            SymbolModeling(firstSymbol, null);
1650
            endModelingGroup.Add(firstSymbol);
1651
            while (endModelingGroup.Count != group.Count)
1652
            {
1653
                foreach (var _symbol in group)
1654
                {
1655
                    if (!endModelingGroup.Contains(_symbol))
1656
                    {
1657
                        foreach (var _connector in _symbol.CONNECTORS)
1658
                        {
1659
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
1660
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
1661
                            {
1662
                                SymbolModeling(_symbol, _connSymbol);
1663
                                endModelingGroup.Add(_symbol);
1664
                                break;
1665
                            }
1666
                        }
1667
                    }
1668
                }
1669
            }
1670
        }
1671

    
1672
        /// <summary>
1673
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
1674
        /// </summary>
1675
        /// <param name="childSymbol"></param>
1676
        /// <param name="parentSymbol"></param>
1677
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
1678
        {
1679
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
1680
            double x1 = 0;
1681
            double x2 = 0;
1682
            double y1 = 0;
1683
            double y2 = 0;
1684
            symbol2d.Range(out x1, out y1, out x2, out y2);
1685

    
1686
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
1687
            if (_LMSymbol != null)
1688
            {
1689
                _LMSymbol.Commit();
1690
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1691
                foreach (var item in childSymbol.ChildSymbols)
1692
                    CreateChildSymbol(item, _LMSymbol, parent);
1693
            }
1694

    
1695

    
1696
            ReleaseCOMObjects(_LMSymbol);
1697
        }
1698
        double index = 0;
1699
        private void NewLineModeling(Line line, bool isBranchModeling = false)
1700
        {
1701
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
1702
                return;
1703

    
1704
            List<Line> group = new List<Line>();
1705
            GetConnectedLineGroup(line, group);
1706
            LineCoordinateCorrection(group);
1707

    
1708
            foreach (var groupLine in group)
1709
            {
1710
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
1711
                {
1712
                    BranchLines.Add(groupLine);
1713
                    continue;
1714
                }
1715

    
1716
                bool diagonal = false;
1717
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
1718
                    diagonal = true;
1719
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
1720
                LMSymbol _LMSymbolStart = null;
1721
                LMSymbol _LMSymbolEnd = null;
1722
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1723
                foreach (var connector in groupLine.CONNECTORS)
1724
                {
1725
                    double x = 0;
1726
                    double y = 0;
1727
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
1728
                    if (connector.ConnectedObject == null)
1729
                    {
1730
                        placeRunInputs.AddPoint(x, y);
1731
                    }
1732
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
1733
                    {
1734
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
1735
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
1736
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1737
                        {
1738
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
1739
                            if (_LMSymbolStart != null)
1740
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
1741
                            else
1742
                                placeRunInputs.AddPoint(x, y);
1743
                        }
1744
                        else
1745
                        {
1746
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
1747
                            if (_LMSymbolEnd != null)
1748
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
1749
                            else
1750
                                placeRunInputs.AddPoint(x, y);
1751
                        }
1752
                    }
1753
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
1754
                    {
1755
                        Line targetLine = connector.ConnectedObject as Line;
1756
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
1757
                        {
1758
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
1759
                            if (targetConnector != null)
1760
                            {
1761
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
1762
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1763
                            }
1764
                            else
1765
                            {
1766
                                placeRunInputs.AddPoint( x, y);
1767
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
1768
                            }
1769
                        }
1770
                        else
1771
                        {
1772
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
1773
                            {
1774
                                index += 0.01;
1775
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1776
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1777
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1778
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1779
                                else
1780
                                {
1781
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
1782
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1783
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1784
                                    else
1785
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1786
                                }
1787
                            }
1788

    
1789
                            placeRunInputs.AddPoint(x, y);
1790

    
1791
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
1792
                            {
1793
                                index += 0.01;
1794
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
1795
                                    placeRunInputs.AddPoint(x, -0.1 - index);
1796
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
1797
                                    placeRunInputs.AddPoint(-0.1 - index, y);
1798
                                else
1799
                                {
1800
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
1801
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
1802
                                        placeRunInputs.AddPoint(-0.1 - index, y);
1803
                                    else
1804
                                        placeRunInputs.AddPoint(x, -0.1 - index);
1805
                                }
1806
                            }
1807
                        }
1808
                    }
1809
                }
1810

    
1811
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1812
                if (_lMConnector != null)
1813
                {
1814
                    _lMConnector.Commit();
1815
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
1816
                    bool bRemodelingStart = false;
1817
                    if (_LMSymbolStart != null)
1818
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
1819
                    bool bRemodelingEnd = false;
1820
                    if (_LMSymbolEnd != null)
1821
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
1822

    
1823
                    if (bRemodelingStart || bRemodelingEnd)
1824
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
1825

    
1826
                    FlowMarkModeling(groupLine);
1827
                    LineNumberModelingOnlyOne(groupLine);
1828

    
1829
                    ReleaseCOMObjects(_lMConnector);
1830
                }
1831
                else if (!isBranchModeling)
1832
                {
1833
                    Log.Write("Main Line Modeling : " + groupLine.UID);
1834
                }
1835

    
1836
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
1837
                x.ConnectedObject != null &&
1838
                x.ConnectedObject.GetType() == typeof(Line) &&
1839
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
1840
                .Select(x => x.ConnectedObject)
1841
                .ToList();
1842

    
1843
                foreach (var item in removeLines)
1844
                    RemoveLineForModeling(item as Line);
1845

    
1846
                if (_LMAItem != null)
1847
                    ReleaseCOMObjects(_LMAItem);
1848
                if (placeRunInputs != null)
1849
                    ReleaseCOMObjects(placeRunInputs);
1850
                if (_LMSymbolStart != null)
1851
                    ReleaseCOMObjects(_LMSymbolStart);
1852
                if (_LMSymbolEnd != null)
1853
                    ReleaseCOMObjects(_LMSymbolEnd);
1854

    
1855
                if (isBranchModeling && BranchLines.Contains(groupLine))
1856
                    BranchLines.Remove(groupLine);
1857
            }
1858
        }
1859

    
1860
        private void RemoveLineForModeling(Line line)
1861
        {
1862
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
1863
            if (modelItem != null)
1864
            {
1865
                foreach (LMRepresentation rep in modelItem.Representations)
1866
                {
1867
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
1868
                    {
1869
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
1870
                        dynamic OID = rep.get_GraphicOID().ToString();
1871
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
1872
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
1873
                        int verticesCount = lineStringGeometry.VertexCount;
1874
                        double[] vertices = null;
1875
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
1876
                        for (int i = 0; i < verticesCount; i++)
1877
                        {
1878
                            double x = 0;
1879
                            double y = 0;
1880
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
1881
                            if (verticesCount == 2 && (x < 0 || y < 0))
1882
                                _placement.PIDRemovePlacement(rep);
1883
                        }
1884
                        ReleaseCOMObjects(_LMConnector);
1885
                    }
1886
                }
1887

    
1888
                ReleaseCOMObjects(modelItem);
1889
            }
1890
        }
1891

    
1892
        private void GetConnectedLineGroup(Line line, List<Line> group)
1893
        {
1894
            if (!group.Contains(line))
1895
                group.Add(line);
1896
            foreach (var connector in line.CONNECTORS)
1897
            {
1898
                if (connector.ConnectedObject != null &&
1899
                    connector.ConnectedObject.GetType() == typeof(Line) &&
1900
                    !group.Contains(connector.ConnectedObject) &&
1901
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
1902
                {
1903
                    Line connLine = connector.ConnectedObject as Line;
1904
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
1905
                    {
1906
                        if (line.CONNECTORS.IndexOf(connector) == 0)
1907
                            group.Insert(0, connLine);
1908
                        else
1909
                            group.Add(connLine);
1910
                        GetConnectedLineGroup(connLine, group);
1911
                    }
1912
                }
1913
            }
1914
        }
1915

    
1916
        private void LineCoordinateCorrection(List<Line> group)
1917
        {
1918
            // 순서대로 전 Item 기준 정렬
1919
            LineCoordinateCorrectionByStart(group);
1920

    
1921
            // 역으로 심볼이 있을 경우 좌표 보정
1922
            LineCoordinateCorrectionForLastLine(group);
1923
        }
1924

    
1925
        private void LineCoordinateCorrectionByStart(List<Line> group)
1926
        {
1927
            for (int i = 0; i < group.Count; i++)
1928
            {
1929
                Line line = group[i];
1930
                if (i == 0)
1931
                {
1932
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1933
                    if (symbolConnector != null)
1934
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
1935
                }
1936
                else if (i != 0)
1937
                {
1938
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
1939
                }
1940
            }
1941
        }
1942

    
1943
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
1944
        {
1945
            Line checkLine = group[group.Count - 1];
1946
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
1947
            if (lastSymbolConnector != null)
1948
            {
1949
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
1950
                for (int i = group.Count - 2; i >= 0; i--)
1951
                {
1952
                    Line line = group[i + 1];
1953
                    Line prevLine = group[i];
1954

    
1955
                    // 같으면 보정
1956
                    if (line.SlopeType == prevLine.SlopeType)
1957
                        LineCoordinateCorrectionByConnItem(prevLine, line);
1958
                    else
1959
                    {
1960
                        if (line.SlopeType == SlopeType.HORIZONTAL)
1961
                        {
1962
                            double prevX = 0;
1963
                            double prevY = 0;
1964
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1965
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
1966

    
1967
                            double x = 0;
1968
                            double y = 0;
1969
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1970
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
1971
                        }
1972
                        else if (line.SlopeType == SlopeType.VERTICAL)
1973
                        {
1974
                            double prevX = 0;
1975
                            double prevY = 0;
1976
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
1977
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
1978

    
1979
                            double x = 0;
1980
                            double y = 0;
1981
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1982
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
1983
                        }
1984
                        break;
1985
                    }
1986
                }
1987
            }
1988
        }
1989

    
1990
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
1991
        {
1992
            double x = 0;
1993
            double y = 0;
1994
            if (connItem.GetType() == typeof(Symbol))
1995
            {
1996
                Symbol targetSymbol = connItem as Symbol;
1997
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
1998
                if (targetConnector != null)
1999
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2000
                else
2001
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2002
            }
2003
            else if (connItem.GetType() == typeof(Line))
2004
            {
2005
                Line targetLine = connItem as Line;
2006
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2007
            }
2008

    
2009
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2010
        }
2011

    
2012
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2013
        {
2014
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2015
            int index = line.CONNECTORS.IndexOf(connector);
2016
            if (index == 0)
2017
            {
2018
                line.SPPID.START_X = x;
2019
                line.SPPID.START_Y = y;
2020
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2021
                    line.SPPID.END_Y = y;
2022
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2023
                    line.SPPID.END_X = x;
2024
            }
2025
            else
2026
            {
2027
                line.SPPID.END_X = x;
2028
                line.SPPID.END_Y = y;
2029
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2030
                    line.SPPID.START_Y = y;
2031
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2032
                    line.SPPID.START_X = x;
2033
            }
2034
        }
2035

    
2036
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2037
        {
2038
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2039
            int index = line.CONNECTORS.IndexOf(connector);
2040
            if (index == 0)
2041
            {
2042
                line.SPPID.START_X = x;
2043
                if (line.SlopeType == SlopeType.VERTICAL)
2044
                    line.SPPID.END_X = x;
2045
            }
2046
            else
2047
            {
2048
                line.SPPID.END_X = x;
2049
                if (line.SlopeType == SlopeType.VERTICAL)
2050
                    line.SPPID.START_X = x;
2051
            }
2052
        }
2053

    
2054
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2055
        {
2056
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2057
            int index = line.CONNECTORS.IndexOf(connector);
2058
            if (index == 0)
2059
            {
2060
                line.SPPID.START_Y = y;
2061
                if (line.SlopeType == SlopeType.HORIZONTAL)
2062
                    line.SPPID.END_Y = y;
2063
            }
2064
            else
2065
            {
2066
                line.SPPID.END_Y = y;
2067
                if (line.SlopeType == SlopeType.HORIZONTAL)
2068
                    line.SPPID.START_Y = y;
2069
            }
2070
        }
2071

    
2072
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2073
        {
2074
            if (symbol != null)
2075
            {
2076
                string repID = symbol.AsLMRepresentation().Id;
2077
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2078
                string lineUID = line.UID;
2079

    
2080
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2081
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2082
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2083

    
2084
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2085
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2086
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2087

    
2088
                if (startSpecBreak != null || startEndBreak != null)
2089
                    result = true;
2090
            }
2091
        }
2092

    
2093
        /// <summary>
2094
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2095
        /// </summary>
2096
        /// <param name="lines"></param>
2097
        /// <param name="prevLMConnector"></param>
2098
        /// <param name="startSymbol"></param>
2099
        /// <param name="endSymbol"></param>
2100
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2101
        {
2102
            string symbolPath = string.Empty;
2103
            #region get symbol path
2104
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2105
            symbolPath = GetSPPIDFileName(modelItem);
2106
            ReleaseCOMObjects(modelItem);
2107
            #endregion
2108
            bool diagonal = false;
2109
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2110
                diagonal = true;
2111
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2112
            LMConnector newConnector = null;
2113
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2114
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2115
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2116
            int verticesCount = lineStringGeometry.VertexCount;
2117
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2118

    
2119
            List<double[]> vertices = new List<double[]>();
2120
            for (int i = 1; i <= verticesCount; i++)
2121
            {
2122
                double x = 0;
2123
                double y = 0;
2124
                lineStringGeometry.GetVertex(i, ref x, ref y);
2125
                vertices.Add(new double[] { x, y });
2126
            }
2127

    
2128
            for (int i = 0; i < vertices.Count; i++)
2129
            {
2130
                double[] points = vertices[i];
2131
                // 시작 심볼이 있고 첫번째 좌표일 때
2132
                if (startSymbol != null && i == 0)
2133
                {
2134
                    if (bStart)
2135
                    {
2136
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2137
                        if (slopeType == SlopeType.HORIZONTAL)
2138
                            placeRunInputs.AddPoint(points[0], -0.1);
2139
                        else if (slopeType == SlopeType.VERTICAL)
2140
                            placeRunInputs.AddPoint(-0.1, points[1]);
2141
                        else
2142
                            placeRunInputs.AddPoint(points[0], -0.1);
2143

    
2144
                        placeRunInputs.AddPoint(points[0], points[1]);
2145
                    }
2146
                    else
2147
                    {
2148
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2149
                    }
2150
                }
2151
                // 마지막 심볼이 있고 마지막 좌표일 때
2152
                else if (endSymbol != null && i == vertices.Count - 1)
2153
                {
2154
                    if (bEnd)
2155
                    {
2156
                        placeRunInputs.AddPoint(points[0], points[1]);
2157

    
2158
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2159
                        if (slopeType == SlopeType.HORIZONTAL)
2160
                            placeRunInputs.AddPoint(points[0], -0.1);
2161
                        else if (slopeType == SlopeType.VERTICAL)
2162
                            placeRunInputs.AddPoint(-0.1, points[1]);
2163
                        else
2164
                            placeRunInputs.AddPoint(points[0], -0.1);
2165
                    }
2166
                    else
2167
                    {
2168
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2169
                    }
2170
                }
2171
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2172
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2173
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2174
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2175
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2176
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2177
                else
2178
                    placeRunInputs.AddPoint(points[0], points[1]);
2179
            }
2180

    
2181
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2182
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2183

    
2184
            ReleaseCOMObjects(placeRunInputs);
2185
            ReleaseCOMObjects(_LMAItem);
2186
            ReleaseCOMObjects(modelItem);
2187

    
2188
            if (newConnector != null)
2189
            {
2190
                newConnector.Commit();
2191
                if (startSymbol != null && bStart)
2192
                {
2193
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2194
                    placeRunInputs = new PlaceRunInputs();
2195
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2196
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2197
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2198
                    if (_LMConnector != null)
2199
                    {
2200
                        _LMConnector.Commit();
2201
                        RemoveConnectorForReModelingLine(newConnector);
2202
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2203
                        ReleaseCOMObjects(_LMConnector);
2204
                    }
2205
                    ReleaseCOMObjects(placeRunInputs);
2206
                    ReleaseCOMObjects(_LMAItem);
2207
                }
2208

    
2209
                if (endSymbol != null && bEnd)
2210
                {
2211
                    if (startSymbol != null)
2212
                    {
2213
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2214
                        newConnector = dicVertices.First().Key;
2215
                    }
2216

    
2217
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2218
                    placeRunInputs = new PlaceRunInputs();
2219
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2220
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2221
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2222
                    if (_LMConnector != null)
2223
                    {
2224
                        _LMConnector.Commit();
2225
                        RemoveConnectorForReModelingLine(newConnector);
2226
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2227
                        ReleaseCOMObjects(_LMConnector);
2228
                    }
2229
                    ReleaseCOMObjects(placeRunInputs);
2230
                    ReleaseCOMObjects(_LMAItem);
2231
                }
2232

    
2233
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2234
                ReleaseCOMObjects(newConnector);
2235
            }
2236

    
2237
            ReleaseCOMObjects(modelItem);
2238
        }
2239

    
2240
        /// <summary>
2241
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2242
        /// </summary>
2243
        /// <param name="connector"></param>
2244
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2245
        {
2246
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2247
            foreach (var item in dicVertices)
2248
            {
2249
                if (item.Value.Count == 2)
2250
                {
2251
                    bool result = false;
2252
                    foreach (var point in item.Value)
2253
                    {
2254
                        if (point[0] < 0 || point[1] < 0)
2255
                        {
2256
                            result = true;
2257
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2258
                            break;
2259
                        }
2260
                    }
2261

    
2262
                    if (result)
2263
                        break;
2264
                }
2265
            }
2266
            foreach (var item in dicVertices)
2267
                ReleaseCOMObjects(item.Key);
2268
        }
2269

    
2270
        /// <summary>
2271
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2272
        /// </summary>
2273
        /// <param name="symbol"></param>
2274
        /// <param name="line"></param>
2275
        /// <returns></returns>
2276
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2277
        {
2278
            LMSymbol _LMSymbol = null;
2279
            foreach (var connector in symbol.CONNECTORS)
2280
            {
2281
                if (connector.CONNECTEDITEM == line.UID)
2282
                {
2283
                    if (connector.Index == 0)
2284
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2285
                    else
2286
                    {
2287
                        ChildSymbol child = null;
2288
                        foreach (var childSymbol in symbol.ChildSymbols)
2289
                        {
2290
                            if (childSymbol.Connectors.Contains(connector))
2291
                                child = childSymbol;
2292
                            else
2293
                                child = GetChildSymbolByConnector(childSymbol, connector);
2294

    
2295
                            if (child != null)
2296
                                break;
2297
                        }
2298

    
2299
                        if (child != null)
2300
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2301
                    }
2302

    
2303
                    break;
2304
                }
2305
            }
2306

    
2307
            return _LMSymbol;
2308
        }
2309

    
2310
        /// <summary>
2311
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2312
        /// </summary>
2313
        /// <param name="item"></param>
2314
        /// <param name="connector"></param>
2315
        /// <returns></returns>
2316
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2317
        {
2318
            foreach (var childSymbol in item.ChildSymbols)
2319
            {
2320
                if (childSymbol.Connectors.Contains(connector))
2321
                    return childSymbol;
2322
                else
2323
                    return GetChildSymbolByConnector(childSymbol, connector);
2324
            }
2325

    
2326
            return null;
2327
        }
2328

    
2329
        /// <summary>
2330
        /// EndBreak 모델링 메서드
2331
        /// </summary>
2332
        /// <param name="endBreak"></param>
2333
        private void EndBreakModeling(EndBreak endBreak)
2334
        {
2335
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2336
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2337
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2338

    
2339
            if (targetLMConnector != null)
2340
            {
2341
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2342
                Array array = null;
2343
                if (point != null)
2344
                    array = new double[] { 0, point[0], point[1] };
2345
                else
2346
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2347
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2348
                if (_LmLabelPersist != null)
2349
                {
2350
                    _LmLabelPersist.Commit();
2351
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2352
                    if (_LmLabelPersist.ModelItemObject != null)
2353
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2354
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2355
                    ReleaseCOMObjects(_LmLabelPersist);
2356
                }
2357
                ReleaseCOMObjects(targetLMConnector);
2358
            }
2359
        }
2360

    
2361
        private LMConnector ReModelingLMConnector(LMConnector connector, string changeSymbolPath = null)
2362
        {
2363
            string symbolPath = string.Empty;
2364
            #region get symbol path
2365
            if (string.IsNullOrEmpty(changeSymbolPath))
2366
            {
2367
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2368
                symbolPath = GetSPPIDFileName(modelItem);
2369
                ReleaseCOMObjects(modelItem);
2370
            }
2371
            else
2372
                symbolPath = changeSymbolPath;
2373
            
2374
            #endregion
2375

    
2376
            LMConnector newConnector = null;
2377
            dynamic OID = connector.get_GraphicOID().ToString();
2378
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2379
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2380
            int verticesCount = lineStringGeometry.VertexCount;
2381
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2382
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2383

    
2384
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2385
            {
2386
                double[] vertices = null;
2387
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2388
                double x = 0;
2389
                double y = 0;
2390
                lineStringGeometry.GetVertex(1, ref x, ref y);
2391

    
2392
                string flowDirection = string.Empty;
2393
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2394
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2395
                    flowDirection = flowAttribute.get_Value().ToString();
2396

    
2397
                if (flowDirection == "End 1 is downstream (Outlet)")
2398
                {
2399
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2400
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2401
                    flowDirection = "End 1 is upstream (Inlet)";
2402
                }
2403
                else
2404
                {
2405
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2406
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2407
                }
2408

    
2409
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2410
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2411
                newConnector.Commit();
2412
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2413
                if (!string.IsNullOrEmpty(flowDirection))
2414
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2415
            }
2416
            else
2417
            {
2418
                List<double[]> vertices = new List<double[]>();
2419
                for (int i = 1; i <= verticesCount; i++)
2420
                {
2421
                    double x = 0;
2422
                    double y = 0;
2423
                    lineStringGeometry.GetVertex(i, ref x, ref y);
2424
                    vertices.Add(new double[] { x, y });
2425
                }
2426

    
2427
                for (int i = 0; i < vertices.Count; i++)
2428
                {
2429
                    double[] points = vertices[i];
2430
                    if (i == 0)
2431
                    {
2432
                        if (connector.ConnectItem1SymbolObject != null)
2433
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, points[0], points[1]);
2434
                        else
2435
                            placeRunInputs.AddPoint(points[0], points[1]);
2436
                    }
2437
                    else if (i == vertices.Count - 1)
2438
                    {
2439
                        if (connector.ConnectItem2SymbolObject != null)
2440
                            placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, points[0], points[1]);
2441
                        else
2442
                            placeRunInputs.AddPoint(points[0], points[1]);
2443
                    }
2444
                    else
2445
                        placeRunInputs.AddPoint(points[0], points[1]);
2446
                }
2447

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

    
2450
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2451
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2452
                newConnector.Commit();
2453
                foreach (var line in lines)
2454
                    line.SPPID.ModelItemId = newConnector.ModelItemID;
2455
            }
2456

    
2457

    
2458
            return newConnector;
2459
        }
2460

    
2461
        /// <summary>
2462
        /// SpecBreak Modeling 메서드
2463
        /// </summary>
2464
        /// <param name="specBreak"></param>
2465
        private void SpecBreakModeling(SpecBreak specBreak)
2466
        {
2467
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2468
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2469

    
2470
            if (upStreamObj != null &&
2471
                downStreamObj != null)
2472
            {
2473
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2474

    
2475
                if (targetLMConnector != null)
2476
                {
2477
                    foreach (var attribute in specBreak.ATTRIBUTES)
2478
                    {
2479
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2480
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2481
                        {
2482
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2483
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2484
                            Array array = null;
2485
                            if (point != null)
2486
                                array = new double[] { 0, point[0], point[1] };
2487
                            else
2488
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2489
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2490

    
2491
                            if (_LmLabelPersist != null)
2492
                            {
2493
                                _LmLabelPersist.Commit();
2494
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2495
                                if (_LmLabelPersist.ModelItemObject != null)
2496
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2497
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2498
                                ReleaseCOMObjects(_LmLabelPersist);
2499
                            }
2500
                        }
2501
                    }
2502
                    ReleaseCOMObjects(targetLMConnector);
2503
                }
2504
            }
2505
        }
2506

    
2507
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2508
        {
2509
            LMConnector targetConnector = null;
2510
            Symbol targetSymbol = targetObj as Symbol;
2511
            Symbol connectedSymbol = connectedObj as Symbol;
2512
            Line targetLine = targetObj as Line;
2513
            Line connectedLine = connectedObj as Line;
2514
            if (targetSymbol != null && connectedSymbol != null)
2515
            {
2516
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2517
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2518

    
2519
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2520
                {
2521
                    if (connector.get_ItemStatus() != "Active")
2522
                        continue;
2523

    
2524
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2525
                    {
2526
                        targetConnector = connector;
2527
                        break;
2528
                    }
2529
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2530
                    {
2531
                        targetConnector = connector;
2532
                        break;
2533
                    }
2534
                }
2535

    
2536
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2537
                {
2538
                    if (connector.get_ItemStatus() != "Active")
2539
                        continue;
2540

    
2541
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2542
                    {
2543
                        targetConnector = connector;
2544
                        break;
2545
                    }
2546
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2547
                    {
2548
                        targetConnector = connector;
2549
                        break;
2550
                    }
2551
                }
2552

    
2553
                ReleaseCOMObjects(targetLMSymbol);
2554
                ReleaseCOMObjects(connectedLMSymbol);
2555
            }
2556
            else if (targetLine != null && connectedLine != null)
2557
            {
2558
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2559
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2560

    
2561
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2562
                {
2563
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2564
                    {
2565
                        if (targetConnector != null)
2566
                            break;
2567

    
2568
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2569
                        {
2570
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2571

    
2572
                            if (IsConnected(_LMConnector, connectedModelItem))
2573
                                targetConnector = _LMConnector;
2574
                            else
2575
                                ReleaseCOMObjects(_LMConnector);
2576
                        }
2577
                    }
2578

    
2579
                    ReleaseCOMObjects(targetModelItem);
2580
                }
2581
            }
2582
            else
2583
            {
2584
                LMSymbol connectedLMSymbol = null;
2585
                if (connectedSymbol != null)
2586
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2587
                else if (targetSymbol != null)
2588
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2589
                else
2590
                {
2591

    
2592
                }
2593
                LMModelItem targetModelItem = null;
2594
                if (targetLine != null)
2595
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2596
                else if (connectedLine != null)
2597
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2598
                else
2599
                {
2600

    
2601
                }
2602
                if (connectedLMSymbol != null && targetModelItem != null)
2603
                {
2604
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2605
                    {
2606
                        if (connector.get_ItemStatus() != "Active")
2607
                            continue;
2608

    
2609
                        if (IsConnected(connector, targetModelItem))
2610
                        {
2611
                            targetConnector = connector;
2612
                            break;
2613
                        }
2614
                    }
2615

    
2616
                    if (targetConnector == null)
2617
                    {
2618
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2619
                        {
2620
                            if (connector.get_ItemStatus() != "Active")
2621
                                continue;
2622

    
2623
                            if (IsConnected(connector, targetModelItem))
2624
                            {
2625
                                targetConnector = connector;
2626
                                break;
2627
                            }
2628
                        }
2629
                    }
2630
                }
2631

    
2632
            }
2633

    
2634
            return targetConnector;
2635
        }
2636

    
2637
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2638
        {
2639
            double[] result = null;
2640
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2641
            {
2642
                return GetConnectorVertices(targetConnector)[0];
2643
            }
2644
            else
2645
            {
2646
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
2647
                {
2648
                    Line line = connObj as Line;
2649
                    LMConnector connectedConnector = null;
2650
                    int connIndex = 0;
2651
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2652
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
2653

    
2654
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
2655

    
2656
                    ReleaseCOMObjects(modelItem);
2657
                    ReleaseCOMObjects(connectedConnector);
2658

    
2659
                    if (vertices.Count > 0)
2660
                    {
2661
                        if (connIndex == 1)
2662
                            return vertices[0];
2663
                        else if (connIndex == 2)
2664
                            return vertices[vertices.Count - 1];
2665
                    }
2666
                }
2667
                else
2668
                {
2669
                    Log.Write("error in GetSegemtPoint");
2670
                }
2671
            }
2672

    
2673
            return result;
2674
        }
2675

    
2676
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
2677
        {
2678
            bool result = false;
2679

    
2680
            foreach (LMRepresentation rep in modelItem.Representations)
2681
            {
2682
                if (result)
2683
                    break;
2684

    
2685
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2686
                {
2687
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2688

    
2689
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2690
                        connector.ConnectItem1SymbolObject != null &&
2691
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2692
                    {
2693
                        result = true;
2694
                        ReleaseCOMObjects(_LMConnector);
2695
                        break;
2696
                    }
2697
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2698
                        connector.ConnectItem2SymbolObject != null &&
2699
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2700
                    {
2701
                        result = true;
2702
                        ReleaseCOMObjects(_LMConnector);
2703
                        break;
2704
                    }
2705
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2706
                        connector.ConnectItem1SymbolObject != null &&
2707
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2708
                    {
2709
                        result = true;
2710
                        ReleaseCOMObjects(_LMConnector);
2711
                        break;
2712
                    }
2713
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2714
                        connector.ConnectItem2SymbolObject != null &&
2715
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2716
                    {
2717
                        result = true;
2718
                        ReleaseCOMObjects(_LMConnector);
2719
                        break;
2720
                    }
2721

    
2722
                    ReleaseCOMObjects(_LMConnector);
2723
                }
2724
            }
2725

    
2726

    
2727
            return result;
2728
        }
2729

    
2730
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
2731
        {
2732
            foreach (LMRepresentation rep in modelItem.Representations)
2733
            {
2734
                if (connectedConnector != null)
2735
                    break;
2736

    
2737
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2738
                {
2739
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2740

    
2741
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
2742
                        connector.ConnectItem1SymbolObject != null &&
2743
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2744
                    {
2745
                        connectedConnector = _LMConnector;
2746
                        connectorIndex = 1;
2747
                        break;
2748
                    }
2749
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
2750
                        connector.ConnectItem2SymbolObject != null &&
2751
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2752
                    {
2753
                        connectedConnector = _LMConnector;
2754
                        connectorIndex = 2;
2755
                        break;
2756
                    }
2757
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2758
                        connector.ConnectItem1SymbolObject != null &&
2759
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
2760
                    {
2761
                        connectedConnector = _LMConnector;
2762
                        connectorIndex = 1;
2763
                        break;
2764
                    }
2765
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
2766
                        connector.ConnectItem2SymbolObject != null &&
2767
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
2768
                    {
2769
                        connectedConnector = _LMConnector;
2770
                        connectorIndex = 2;
2771
                        break;
2772
                    }
2773

    
2774
                    if (connectedConnector == null)
2775
                        ReleaseCOMObjects(_LMConnector);
2776
                }
2777
            }
2778
        }
2779

    
2780
        /// <summary>
2781
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
2782
        /// </summary>
2783
        /// <param name="modelItemID1"></param>
2784
        /// <param name="modelItemID2"></param>
2785
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
2786
        {
2787
            try
2788
            {
2789
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
2790
                _LMAItem item1 = modelItem1.AsLMAItem();
2791
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
2792
                _LMAItem item2 = modelItem2.AsLMAItem();
2793

    
2794
                // item2가 item1으로 조인
2795
                _placement.PIDJoinRuns(ref item1, ref item2);
2796
                item1.Commit();
2797
                item2.Commit();
2798

    
2799
                string beforeID = string.Empty;
2800
                string afterID = string.Empty;
2801

    
2802
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
2803
                {
2804
                    beforeID = modelItem2.Id;
2805
                    afterID = modelItem1.Id;
2806
                    survivorId = afterID;
2807
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
2808
                    if (attribute != null)
2809
                        attribute.set_Value("End 1 is upstream (Inlet)");
2810
                }
2811
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
2812
                {
2813
                    beforeID = modelItem1.Id;
2814
                    afterID = modelItem2.Id;
2815
                    survivorId = afterID;
2816
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
2817
                    if (attribute != null)
2818
                        attribute.set_Value("End 1 is upstream (Inlet)");
2819
                }
2820
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
2821
                    survivorId = null;
2822
                else
2823
                {
2824
                    Log.Write("잘못된 경우");
2825
                    survivorId = null;
2826
                }
2827

    
2828
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
2829
                {
2830
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
2831
                    foreach (var line in lines)
2832
                        line.SPPID.ModelItemId = afterID;
2833
                }
2834

    
2835
                ReleaseCOMObjects(modelItem1);
2836
                ReleaseCOMObjects(item1);
2837
                ReleaseCOMObjects(modelItem2);
2838
                ReleaseCOMObjects(item2);
2839
            }
2840
            catch (Exception ex)
2841
            {
2842
                Log.Write("Join Error");
2843
                Log.Write(ex.Message);
2844
            }
2845
        }
2846

    
2847
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
2848
        {
2849
            List<string> modelItemIDs = new List<string>();
2850
            foreach (LMConnector connector in symbol.Avoid1Connectors)
2851
            {
2852
                LMModelItem modelItem = connector.ModelItemObject;
2853
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2854
                    modelItemIDs.Add(modelItem.Id);
2855
                ReleaseCOMObjects(modelItem);
2856
                ReleaseCOMObjects(connector);
2857
            }
2858

    
2859
            foreach (LMConnector connector in symbol.Avoid2Connectors)
2860
            {
2861
                LMModelItem modelItem = connector.ModelItemObject;
2862
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId)
2863
                    modelItemIDs.Add(modelItem.Id);
2864
                ReleaseCOMObjects(modelItem);
2865
                ReleaseCOMObjects(connector);
2866
            }
2867

    
2868

    
2869
            List<string> result = new List<string>();
2870
            modelItemIDs = modelItemIDs.Distinct().ToList();
2871
            string originalName = GetSPPIDFileName(modelId);
2872
            bool existZeroLength = false;
2873
            foreach (var item in modelItemIDs)
2874
            {
2875
                string fileName = GetSPPIDFileName(item);
2876
                if (originalName == fileName)
2877
                    result.Add(item);
2878
                else
2879
                {
2880
                    LMConnector connector = GetLMConnectorOnlyOne(item);
2881
                    if (connector != null && Convert.ToBoolean(connector.get_IsZeroLength()) && connector.LabelPersists.Count == 0)
2882
                    {
2883
                        result.Add(item);
2884
                        ReleaseCOMObjects(connector);
2885
                        existZeroLength = true;
2886
                    }
2887
                }
2888
            }
2889

    
2890
            if (result.Count == 1 && existZeroLength)
2891
            {
2892
                LMConnector connector = GetLMConnectorOnlyOne(result[0]);
2893
                LMConnector newConnector = ReModelingLMConnector(connector, originalName);
2894
                result.Clear();
2895
                if (newConnector != null)
2896
                    result.Add(newConnector.ModelItemID);
2897

    
2898
                ReleaseCOMObjects(connector);
2899
                connector = null;
2900
                ReleaseCOMObjects(newConnector);
2901
                newConnector = null;
2902
            }
2903
            
2904
            return result;
2905
        }
2906

    
2907
        /// <summary>
2908
        /// PipeRun의 좌표를 가져오는 메서드
2909
        /// </summary>
2910
        /// <param name="modelId"></param>
2911
        /// <returns></returns>
2912
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId)
2913
        {
2914
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
2915
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
2916

    
2917
            if (modelItem != null)
2918
            {
2919
                foreach (LMRepresentation rep in modelItem.Representations)
2920
                {
2921
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2922
                    {
2923
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2924
                        connectorVertices.Add(_LMConnector, new List<double[]>());
2925
                        dynamic OID = rep.get_GraphicOID().ToString();
2926
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2927
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2928
                        int verticesCount = lineStringGeometry.VertexCount;
2929
                        double[] vertices = null;
2930
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2931
                        for (int i = 0; i < verticesCount; i++)
2932
                        {
2933
                            double x = 0;
2934
                            double y = 0;
2935
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2936
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
2937
                        }
2938
                    }
2939
                }
2940

    
2941
                ReleaseCOMObjects(modelItem);
2942
            }
2943

    
2944
            return connectorVertices;
2945
        }
2946

    
2947
        private List<double[]> GetConnectorVertices(LMConnector connector)
2948
        {
2949
            List<double[]> vertices = new List<double[]>();
2950
            if (connector != null)
2951
            {
2952
                dynamic OID = connector.get_GraphicOID().ToString();
2953
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2954
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2955
                int verticesCount = lineStringGeometry.VertexCount;
2956
                double[] value = null;
2957
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
2958
                for (int i = 0; i < verticesCount; i++)
2959
                {
2960
                    double x = 0;
2961
                    double y = 0;
2962
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2963
                    vertices.Add(new double[] { x, y });
2964
                }
2965
            }
2966
            return vertices;
2967
        }
2968

    
2969
        /// <summary>
2970
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
2971
        /// </summary>
2972
        /// <param name="connectorVertices"></param>
2973
        /// <param name="connX"></param>
2974
        /// <param name="connY"></param>
2975
        /// <returns></returns>
2976
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
2977
        {
2978
            double length = double.MaxValue;
2979
            LMConnector targetConnector = null;
2980
            foreach (var item in connectorVertices)
2981
            {
2982
                List<double[]> points = item.Value;
2983
                for (int i = 0; i < points.Count - 1; i++)
2984
                {
2985
                    double[] point1 = points[i];
2986
                    double[] point2 = points[i + 1];
2987
                    double x1 = Math.Min(point1[0], point2[0]);
2988
                    double y1 = Math.Min(point1[1], point2[1]);
2989
                    double x2 = Math.Max(point1[0], point2[0]);
2990
                    double y2 = Math.Max(point1[1], point2[1]);
2991

    
2992
                    if ((x1 <= connX && x2 >= connX) ||
2993
                        (y1 <= connY && y2 >= connY))
2994
                    {
2995
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
2996
                        if (length >= distance)
2997
                        {
2998
                            targetConnector = item.Key;
2999
                            length = distance;
3000
                        }
3001

    
3002
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3003
                        if (length >= distance)
3004
                        {
3005
                            targetConnector = item.Key;
3006
                            length = distance;
3007
                        }
3008
                    }
3009
                }
3010
            }
3011

    
3012
            // 못찾았을때.
3013
            length = double.MaxValue;
3014
            if (targetConnector == null)
3015
            {
3016
                foreach (var item in connectorVertices)
3017
                {
3018
                    List<double[]> points = item.Value;
3019

    
3020
                    foreach (double[] point in points)
3021
                    {
3022
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3023
                        if (length >= distance)
3024
                        {
3025
                            targetConnector = item.Key;
3026
                            length = distance;
3027
                        }
3028
                    }
3029
                }
3030
            }
3031

    
3032
            return targetConnector;
3033
        }
3034

    
3035
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3036
        {
3037
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3038
            if (vertices.Count == 0)
3039
                return null;
3040

    
3041
            double length = double.MaxValue;
3042
            LMConnector targetConnector = null;
3043
            double[] resultPoint = null;
3044
            List<double[]> targetVertices = null;
3045

    
3046
            // Vertices 포인트에 제일 가까운곳
3047
            foreach (var item in vertices)
3048
            {
3049
                List<double[]> points = item.Value;
3050
                for (int i = 0; i < points.Count; i++)
3051
                {
3052
                    double[] point = points[i];
3053
                    double tempX = point[0];
3054
                    double tempY = point[1];
3055

    
3056
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3057
                    if (length >= distance)
3058
                    {
3059
                        targetConnector = item.Key;
3060
                        length = distance;
3061
                        resultPoint = point;
3062
                        targetVertices = item.Value;
3063
                    }
3064
                }
3065
            }
3066

    
3067
            // Vertices Cross에 제일 가까운곳
3068
            foreach (var item in vertices)
3069
            {
3070
                List<double[]> points = item.Value;
3071
                for (int i = 0; i < points.Count - 1; i++)
3072
                {
3073
                    double[] point1 = points[i];
3074
                    double[] point2 = points[i + 1];
3075

    
3076
                    double maxLineX = Math.Max(point1[0], point2[0]);
3077
                    double minLineX = Math.Min(point1[0], point2[0]);
3078
                    double maxLineY = Math.Max(point1[1], point2[1]);
3079
                    double minLineY = Math.Min(point1[1], point2[1]);
3080

    
3081
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3082

    
3083
                    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]);
3084
                    if (crossingPoint != null)
3085
                    {
3086
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3087
                        if (length >= distance)
3088
                        {
3089
                            if (slope == SlopeType.Slope &&
3090
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3091
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3092
                            {
3093
                                targetConnector = item.Key;
3094
                                length = distance;
3095
                                resultPoint = crossingPoint;
3096
                                targetVertices = item.Value;
3097
                            }
3098
                            else if (slope == SlopeType.HORIZONTAL &&
3099
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3100
                            {
3101
                                targetConnector = item.Key;
3102
                                length = distance;
3103
                                resultPoint = crossingPoint;
3104
                                targetVertices = item.Value;
3105
                            }
3106
                            else if (slope == SlopeType.VERTICAL &&
3107
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3108
                            {
3109
                                targetConnector = item.Key;
3110
                                length = distance;
3111
                                resultPoint = crossingPoint;
3112
                                targetVertices = item.Value;
3113
                            }
3114
                        }
3115
                    }
3116
                }
3117
            }
3118

    
3119
            foreach (var item in vertices)
3120
                if (item.Key != null && item.Key != targetConnector)
3121
                    ReleaseCOMObjects(item.Key);
3122

    
3123
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3124
            {
3125
                double tempResultX = resultPoint[0];
3126
                double tempResultY = resultPoint[1];
3127
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3128

    
3129
                GridSetting gridSetting = GridSetting.GetInstance();
3130

    
3131
                for (int i = 0; i < targetVertices.Count; i++)
3132
                {
3133
                    double[] point = targetVertices[i];
3134
                    double tempX = targetVertices[i][0];
3135
                    double tempY = targetVertices[i][1];
3136
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3137
                    if (tempX == tempResultX && tempY == tempResultY)
3138
                    {
3139
                        if (i == 0)
3140
                        {
3141
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3142
                            bool containZeroLength = false;
3143
                            if (connSymbol != null)
3144
                            {
3145
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3146
                                {
3147
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3148
                                        containZeroLength = true;
3149
                                }
3150
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3151
                                {
3152
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3153
                                        containZeroLength = true;
3154
                                }
3155
                            }
3156

    
3157
                            if (connSymbol == null ||
3158
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3159
                                containZeroLength)
3160
                            {
3161
                                bool bCalcX = false;
3162
                                bool bCalcY = false;
3163
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3164
                                    bCalcX = true;
3165
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3166
                                    bCalcY = true;
3167
                                else
3168
                                {
3169
                                    bCalcX = true;
3170
                                    bCalcY = true;
3171
                                }
3172

    
3173
                                if (bCalcX)
3174
                                {
3175
                                    double nextX = targetVertices[i + 1][0];
3176
                                    double newX = 0;
3177
                                    if (nextX > tempX)
3178
                                    {
3179
                                        newX = tempX + gridSetting.Length;
3180
                                        if (newX > nextX)
3181
                                            newX = (point[0] + nextX) / 2;
3182
                                    }
3183
                                    else
3184
                                    {
3185
                                        newX = tempX - gridSetting.Length;
3186
                                        if (newX < nextX)
3187
                                            newX = (point[0] + nextX) / 2;
3188
                                    }
3189
                                    resultPoint = new double[] { newX, resultPoint[1] };
3190
                                }
3191

    
3192
                                if (bCalcY)
3193
                                {
3194
                                    double nextY = targetVertices[i + 1][1];
3195
                                    double newY = 0;
3196
                                    if (nextY > tempY)
3197
                                    {
3198
                                        newY = tempY + gridSetting.Length;
3199
                                        if (newY > nextY)
3200
                                            newY = (point[1] + nextY) / 2;
3201
                                    }
3202
                                    else
3203
                                    {
3204
                                        newY = tempY - gridSetting.Length;
3205
                                        if (newY < nextY)
3206
                                            newY = (point[1] + nextY) / 2;
3207
                                    }
3208
                                    resultPoint = new double[] { resultPoint[0], newY };
3209
                                }
3210
                            }
3211
                        }
3212
                        else if (i == targetVertices.Count - 1)
3213
                        {
3214
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3215
                            bool containZeroLength = false;
3216
                            if (connSymbol != null)
3217
                            {
3218
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3219
                                {
3220
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3221
                                        containZeroLength = true;
3222
                                }
3223
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3224
                                {
3225
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3226
                                        containZeroLength = true;
3227
                                }
3228
                            }
3229

    
3230
                            if (connSymbol == null ||
3231
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3232
                                containZeroLength)
3233
                            {
3234
                                bool bCalcX = false;
3235
                                bool bCalcY = false;
3236
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3237
                                    bCalcX = true;
3238
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3239
                                    bCalcY = true;
3240
                                else
3241
                                {
3242
                                    bCalcX = true;
3243
                                    bCalcY = true;
3244
                                }
3245

    
3246
                                if (bCalcX)
3247
                                {
3248
                                    double nextX = targetVertices[i - 1][0];
3249
                                    double newX = 0;
3250
                                    if (nextX > tempX)
3251
                                    {
3252
                                        newX = tempX + gridSetting.Length;
3253
                                        if (newX > nextX)
3254
                                            newX = (point[0] + nextX) / 2;
3255
                                    }
3256
                                    else
3257
                                    {
3258
                                        newX = tempX - gridSetting.Length;
3259
                                        if (newX < nextX)
3260
                                            newX = (point[0] + nextX) / 2;
3261
                                    }
3262
                                    resultPoint = new double[] { newX, resultPoint[1] };
3263
                                }
3264

    
3265
                                if (bCalcY)
3266
                                {
3267
                                    double nextY = targetVertices[i - 1][1];
3268
                                    double newY = 0;
3269
                                    if (nextY > tempY)
3270
                                    {
3271
                                        newY = tempY + gridSetting.Length;
3272
                                        if (newY > nextY)
3273
                                            newY = (point[1] + nextY) / 2;
3274
                                    }
3275
                                    else
3276
                                    {
3277
                                        newY = tempY - gridSetting.Length;
3278
                                        if (newY < nextY)
3279
                                            newY = (point[1] + nextY) / 2;
3280
                                    }
3281
                                    resultPoint = new double[] { resultPoint[0], newY };
3282
                                }
3283
                            }
3284
                        }
3285
                        break;
3286
                    }
3287
                }
3288
            }
3289

    
3290
            x = resultPoint[0];
3291
            y = resultPoint[1];
3292

    
3293
            return targetConnector;
3294
        }
3295

    
3296
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3297
        {
3298
            LMConnector result = null;
3299
            List<LMConnector> connectors = new List<LMConnector>();
3300
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3301

    
3302
            if (modelItem != null)
3303
            {
3304
                foreach (LMRepresentation rep in modelItem.Representations)
3305
                {
3306
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3307
                        connectors.Add(dataSource.GetConnector(rep.Id));
3308
                }
3309

    
3310
                ReleaseCOMObjects(modelItem);
3311
            }
3312

    
3313
            if (connectors.Count == 1)
3314
                result = connectors[0];
3315
            else
3316
                foreach (var item in connectors)
3317
                    ReleaseCOMObjects(item);
3318

    
3319
            return result;
3320
        }
3321

    
3322
        /// <summary>
3323
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3324
        /// </summary>
3325
        /// <param name="lineNumber"></param>
3326
        private void LineNumberModelingOnlyOne(Line line)
3327
        {
3328
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3329
            if (lineNumber != null)
3330
            {
3331
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3332
                if (connectedLMConnector != null)
3333
                {
3334
                    double x = 0;
3335
                    double y = 0;
3336
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3337

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

    
3341
                    if (_LmLabelPresist != null)
3342
                    {
3343
                        _LmLabelPresist.Commit();
3344
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3345
                        ReleaseCOMObjects(_LmLabelPresist);
3346
                    }
3347
                }
3348
            }
3349
        }
3350

    
3351
        private void LineNumberModeling(LineNumber lineNumber)
3352
        {
3353
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3354
            if (line != null)
3355
            {
3356
                double x = 0;
3357
                double y = 0;
3358
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3359

    
3360
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3361
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3362
                if (connectedLMConnector != null)
3363
                {
3364
                    Array points = new double[] { 0, x, y };
3365
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3366

    
3367
                    if (_LmLabelPresist != null)
3368
                    {
3369
                        _LmLabelPresist.Commit();
3370
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3371
                        ReleaseCOMObjects(_LmLabelPresist);
3372
                    }
3373
                }
3374

    
3375
                foreach (var item in connectorVertices)
3376
                    ReleaseCOMObjects(item.Key);
3377
            }
3378
        }
3379
        /// <summary>
3380
        /// Flow Mark Modeling
3381
        /// </summary>
3382
        /// <param name="line"></param>
3383
        private void FlowMarkModeling(Line line)
3384
        {
3385
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3386
            {
3387
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3388
                if (connector != null)
3389
                {
3390
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
3391
                    List<double[]> vertices = GetConnectorVertices(connector);
3392
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
3393
                    double[] point = vertices[vertices.Count - 1];
3394
                    Array array = new double[] { 0, point[0], point[1] };
3395
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
3396
                    if (_LMLabelPersist != null)
3397
                    {
3398
                        _LMLabelPersist.Commit();
3399
                        ReleaseCOMObjects(_LMLabelPersist);
3400
                    }
3401
                        
3402
                }
3403
            }
3404
        }
3405

    
3406
        /// <summary>
3407
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
3408
        /// </summary>
3409
        /// <param name="lineNumber"></param>
3410
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
3411
        {
3412
            foreach (LineRun run in lineNumber.RUNS)
3413
            {
3414
                foreach (var item in run.RUNITEMS)
3415
                {
3416
                    if (item.GetType() == typeof(Symbol))
3417
                    {
3418
                        Symbol symbol = item as Symbol;
3419
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3420
                        if (_LMSymbol != null)
3421
                        {
3422
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3423

    
3424
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3425
                            {
3426
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3427
                                {
3428
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3429
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3430
                                    {
3431
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3432
                                        if (_LMAAttribute != null)
3433
                                        {
3434
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3435
                                                _LMAAttribute.set_Value(attribute.VALUE);
3436
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3437
                                                _LMAAttribute.set_Value(attribute.VALUE);
3438
                                        }
3439
                                    }
3440
                                }
3441
                                _LMModelItem.Commit();
3442
                            }
3443
                            if (_LMModelItem != null)
3444
                                ReleaseCOMObjects(_LMModelItem);
3445
                        }
3446
                        if (_LMSymbol != null)
3447
                            ReleaseCOMObjects(_LMSymbol);
3448
                    }
3449
                    else if (item.GetType() == typeof(Line))
3450
                    {
3451
                        Line line = item as Line;
3452
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
3453
                        {
3454
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3455
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3456
                            {
3457
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3458
                                {
3459
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3460
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3461
                                    {
3462
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3463
                                        if (_LMAAttribute != null)
3464
                                        {
3465
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3466
                                                _LMAAttribute.set_Value(attribute.VALUE);
3467
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3468
                                                _LMAAttribute.set_Value(attribute.VALUE);
3469

    
3470
                                        }
3471
                                    }
3472
                                }
3473
                                _LMModelItem.Commit();
3474
                            }
3475
                            if (_LMModelItem != null)
3476
                                ReleaseCOMObjects(_LMModelItem);
3477
                            endLine.Add(line.SPPID.ModelItemId);
3478
                        }
3479
                    }
3480
                }
3481
            }
3482
        }
3483

    
3484
        /// <summary>
3485
        /// Symbol Attribute 입력 메서드
3486
        /// </summary>
3487
        /// <param name="item"></param>
3488
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
3489
        {
3490
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
3491
            string sRep = null;
3492
            if (targetItem.GetType() == typeof(Symbol))
3493
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
3494
            else if (targetItem.GetType() == typeof(Equipment))
3495
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
3496

    
3497
            if (!string.IsNullOrEmpty(sRep))
3498
            {
3499
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
3500
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3501
                LMAAttributes _Attributes = _LMModelItem.Attributes;
3502
                
3503
                foreach (var item in targetAttributes)
3504
                {
3505
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
3506
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
3507
                    {
3508
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
3509
                        if (_Attribute != null)
3510
                        {
3511
                            object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
3512
                            if (associItem != null)
3513
                            {
3514
                                if (associItem.GetType() == typeof(Text))
3515
                                {
3516
                                    Text text = associItem as Text;
3517
                                    text.SPPID.RepresentationId = "Attribute";
3518
                                }
3519
                                else if (associItem.GetType() == typeof(Note))
3520
                                {
3521
                                    Note note = associItem as Note;
3522
                                    note.SPPID.RepresentationId = "Attribute";
3523
                                }
3524
                            }
3525
                            _Attribute.set_Value(item.VALUE);
3526
                            // OPC 일경우 Attribute 저장
3527
                            if (targetItem.GetType() == typeof(Symbol))
3528
                            {
3529
                                Symbol symbol = targetItem as Symbol;
3530
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
3531
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
3532
                            }
3533
                        }
3534
                    }
3535
                }
3536
                _LMModelItem.Commit();
3537

    
3538
                ReleaseCOMObjects(_Attributes);
3539
                ReleaseCOMObjects(_LMModelItem);
3540
                ReleaseCOMObjects(_LMSymbol);
3541
            }
3542
        }
3543

    
3544
        /// <summary>
3545
        /// Input SpecBreak Attribute
3546
        /// </summary>
3547
        /// <param name="specBreak"></param>
3548
        private void InputSpecBreakAttribute(SpecBreak specBreak)
3549
        {
3550
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3551
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3552

    
3553
            if (upStreamObj != null &&
3554
                downStreamObj != null)
3555
            {
3556
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3557

    
3558
                if (targetLMConnector != null)
3559
                {
3560
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
3561
                    {
3562
                        string symbolPath = _LMLabelPersist.get_FileName();
3563
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
3564
                        if (mapping != null)
3565
                        {
3566
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
3567
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3568
                            {
3569
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
3570
                                if (values.Length == 2)
3571
                                {
3572
                                    string upStreamValue = values[0];
3573
                                    string downStreamValue = values[1];
3574

    
3575
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
3576
                                }
3577
                            }
3578
                        }
3579
                    }
3580

    
3581
                    ReleaseCOMObjects(targetLMConnector);
3582
                }
3583
            }
3584

    
3585

    
3586
            #region 내부에서만 쓰는 메서드
3587
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
3588
            {
3589
                Symbol upStreamSymbol = _upStreamObj as Symbol;
3590
                Line upStreamLine = _upStreamObj as Line;
3591
                Symbol downStreamSymbol = _downStreamObj as Symbol;
3592
                Line downStreamLine = _downStreamObj as Line;
3593
                // 둘다 Line일 경우
3594
                if (upStreamLine != null && downStreamLine != null)
3595
                {
3596
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3597
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3598
                }
3599
                // 둘다 Symbol일 경우
3600
                else if (upStreamSymbol != null && downStreamSymbol != null)
3601
                {
3602
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
3603
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3604
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3605

    
3606
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3607
                    {
3608
                        if (connector.get_ItemStatus() != "Active")
3609
                            continue;
3610

    
3611
                        if (connector.Id != zeroLenthConnector.Id)
3612
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3613
                    }
3614

    
3615
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3616
                    {
3617
                        if (connector.get_ItemStatus() != "Active")
3618
                            continue;
3619

    
3620
                        if (connector.Id != zeroLenthConnector.Id)
3621
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3622
                    }
3623

    
3624
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3625
                    {
3626
                        if (connector.get_ItemStatus() != "Active")
3627
                            continue;
3628

    
3629
                        if (connector.Id != zeroLenthConnector.Id)
3630
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3631
                    }
3632

    
3633
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3634
                    {
3635
                        if (connector.get_ItemStatus() != "Active")
3636
                            continue;
3637

    
3638
                        if (connector.Id != zeroLenthConnector.Id)
3639
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3640
                    }
3641

    
3642
                    ReleaseCOMObjects(zeroLenthConnector);
3643
                    ReleaseCOMObjects(upStreamLMSymbol);
3644
                    ReleaseCOMObjects(downStreamLMSymbol);
3645
                }
3646
                else if (upStreamSymbol != null && downStreamLine != null)
3647
                {
3648
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
3649
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
3650
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
3651

    
3652
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3653
                    {
3654
                        if (connector.get_ItemStatus() != "Active")
3655
                            continue;
3656

    
3657
                        if (connector.Id == zeroLenthConnector.Id)
3658
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3659
                    }
3660

    
3661
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3662
                    {
3663
                        if (connector.get_ItemStatus() != "Active")
3664
                            continue;
3665

    
3666
                        if (connector.Id == zeroLenthConnector.Id)
3667
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3668
                    }
3669

    
3670
                    ReleaseCOMObjects(zeroLenthConnector);
3671
                    ReleaseCOMObjects(upStreamLMSymbol);
3672
                }
3673
                else if (upStreamLine != null && downStreamSymbol != null)
3674
                {
3675
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
3676
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
3677
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
3678

    
3679
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3680
                    {
3681
                        if (connector.get_ItemStatus() != "Active")
3682
                            continue;
3683

    
3684
                        if (connector.Id == zeroLenthConnector.Id)
3685
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3686
                    }
3687

    
3688
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3689
                    {
3690
                        if (connector.get_ItemStatus() != "Active")
3691
                            continue;
3692

    
3693
                        if (connector.Id == zeroLenthConnector.Id)
3694
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3695
                    }
3696

    
3697
                    ReleaseCOMObjects(zeroLenthConnector);
3698
                    ReleaseCOMObjects(downStreamLMSymbol);
3699
                }
3700
            }
3701

    
3702
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
3703
            {
3704
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3705
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3706
                {
3707
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3708
                    if (_LMAAttribute != null)
3709
                    {
3710
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3711
                            _LMAAttribute.set_Value(value);
3712
                        else if (_LMAAttribute.get_Value() != value)
3713
                            _LMAAttribute.set_Value(value);
3714
                    }
3715

    
3716
                    _LMModelItem.Commit();
3717
                }
3718
                if (_LMModelItem != null)
3719
                    ReleaseCOMObjects(_LMModelItem);
3720
            }
3721

    
3722
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
3723
            {
3724
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
3725
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3726
                {
3727
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
3728
                    if (_LMAAttribute != null)
3729
                    {
3730
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3731
                            _LMAAttribute.set_Value(value);
3732
                        else if (_LMAAttribute.get_Value() != value)
3733
                            _LMAAttribute.set_Value(value);
3734
                    }
3735

    
3736
                    _LMModelItem.Commit();
3737
                }
3738
                if (_LMModelItem != null)
3739
                    ReleaseCOMObjects(_LMModelItem);
3740
            }
3741
            #endregion
3742
        }
3743

    
3744
        /// <summary>
3745
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
3746
        /// </summary>
3747
        /// <param name="text"></param>
3748
        private void TextModeling(Text text, List<Text> correctList)
3749
        {
3750
            LMSymbol _LMSymbol = null;
3751
            LMConnector connectedLMConnector = null;
3752
            //if (text.ASSOCIATION && !string.IsNullOrEmpty(text.OWNER) && text.OWNER != "None")
3753
            if (text.ASSOCIATION)
3754
            {
3755
                object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
3756
                if (owner != null && owner.GetType() == typeof(Symbol))
3757
                {
3758
                    Symbol symbol = owner as Symbol;
3759
                    _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3760
                    if (_LMSymbol != null)
3761
                    {
3762
                        BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3763
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3764
                        {
3765
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3766

    
3767
                            if (mapping != null)
3768
                            {
3769
                                double x = 0;
3770
                                double y = 0;
3771

    
3772
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3773
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
3774
                                Array array = new double[] { 0, x, y };
3775
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3776
                                if (_LMLabelPersist != null)
3777
                                {
3778
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3779
                                    _LMLabelPersist.Commit();
3780
                                    ReleaseCOMObjects(_LMLabelPersist);
3781
                                }
3782
                            }
3783
                        }
3784
                    }
3785
                }
3786
                else if (owner != null && owner.GetType() == typeof(Line))
3787
                {
3788
                    Line line = owner as Line;
3789
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3790
                    connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
3791

    
3792
                    if (connectedLMConnector != null)
3793
                    {
3794
                        BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
3795
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3796
                        {
3797
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
3798

    
3799
                            if (mapping != null)
3800
                            {
3801
                                double x = 0;
3802
                                double y = 0;
3803
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
3804
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
3805
                                Array array = new double[] { 0, x, y };
3806

    
3807
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3808
                                if (_LMLabelPersist != null)
3809
                                {
3810
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
3811
                                    _LMLabelPersist.Commit();
3812
                                    ReleaseCOMObjects(_LMLabelPersist);
3813
                                }
3814
                            }
3815
                        }
3816
                    }
3817
                }
3818
            }
3819
            else
3820
            {
3821
                LMItemNote _LMItemNote = null;
3822
                LMAAttribute _LMAAttribute = null;
3823

    
3824
                double x = 0;
3825
                double y = 0;
3826
                double angle = text.ANGLE;
3827
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
3828

    
3829
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
3830
                text.SPPID.SPPID_X = x;
3831
                text.SPPID.SPPID_Y = y;
3832

    
3833
                _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
3834
                if (_LMSymbol != null)
3835
                {
3836
                    _LMSymbol.Commit();
3837
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3838
                    if (_LMItemNote != null)
3839
                    {
3840
                        _LMItemNote.Commit();
3841
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3842
                        if (_LMAAttribute != null)
3843
                        {
3844
                            _LMAAttribute.set_Value(text.VALUE);
3845
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3846
                            _LMItemNote.Commit();
3847

    
3848

    
3849
                            double[] range = null;
3850
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
3851
                            {
3852
                                double[] temp = null;
3853
                                GetSPPIDSymbolRange(labelPersist, ref temp);
3854
                                if (temp != null)
3855
                                {
3856
                                    if (range == null)
3857
                                        range = temp;
3858
                                    else
3859
                                    {
3860
                                        range = new double[] {
3861
                                            Math.Min(range[0], temp[0]),
3862
                                            Math.Min(range[1], temp[1]),
3863
                                            Math.Max(range[2], temp[2]),
3864
                                            Math.Max(range[3], temp[3])
3865
                                        };
3866
                                    }
3867
                                }
3868
                            }
3869
                            if (range != null)
3870
                                correctList.Add(text);
3871
                            text.SPPID.Range = range;
3872

    
3873

    
3874
                            if (_LMAAttribute != null)
3875
                                ReleaseCOMObjects(_LMAAttribute);
3876
                            if (_LMItemNote != null)
3877
                                ReleaseCOMObjects(_LMItemNote);
3878
                        }
3879
                    }
3880
                }
3881
            }
3882
            if (_LMSymbol != null)
3883
                ReleaseCOMObjects(_LMSymbol);
3884
        }
3885

    
3886
        private void TextCorrectModeling(Text text, List<Text> endList)
3887
        {
3888
            bool needRemodeling = false;
3889
            bool loop = true;
3890
            GridSetting gridSetting = GridSetting.GetInstance();
3891
            while (loop)
3892
            {
3893
                loop = false;
3894
                foreach (var overlapText in endList)
3895
                {
3896
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
3897
                    {
3898
                        double tempX = 0;
3899
                        double tempY = 0;
3900
                        bool overlapX = false;
3901
                        bool overlapY = false;
3902
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
3903
                        double angle = SPPIDUtil.CalcAngle(text.LOCATION_X, text.LOCATION_Y, overlapText.LOCATION_X, overlapText.LOCATION_Y);
3904
                        if (overlapY && angle >= 45)
3905
                        {
3906
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
3907
                            double move = gridSetting.Length * count;
3908
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
3909
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
3910
                            needRemodeling = true;
3911
                            loop = true;
3912
                        }
3913
                        if (overlapX && angle <= 45)
3914
                        {
3915
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
3916
                            double move = gridSetting.Length * count;
3917
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
3918
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
3919
                            needRemodeling = true;
3920
                            loop = true;
3921
                        }
3922
                    }
3923
                }
3924
            }
3925
            
3926

    
3927
            if (needRemodeling)
3928
            {
3929
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
3930
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
3931
                text.SPPID.RepresentationId = null;
3932

    
3933
                LMItemNote _LMItemNote = null;
3934
                LMAAttribute _LMAAttribute = null;
3935
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
3936
                if (_LMSymbol != null)
3937
                {
3938
                    _LMSymbol.Commit();
3939
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3940
                    if (_LMItemNote != null)
3941
                    {
3942
                        _LMItemNote.Commit();
3943
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3944
                        if (_LMAAttribute != null)
3945
                        {
3946
                            _LMAAttribute.set_Value(text.VALUE);
3947
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
3948
                            _LMItemNote.Commit();
3949

    
3950
                            ReleaseCOMObjects(_LMAAttribute);
3951
                            ReleaseCOMObjects(_LMItemNote);
3952
                        }
3953
                    }
3954
                }
3955

    
3956
                ReleaseCOMObjects(symbol);
3957
                symbol = null;
3958
                ReleaseCOMObjects(_LMItemNote);
3959
                _LMItemNote = null;
3960
                ReleaseCOMObjects(_LMAAttribute);
3961
                _LMAAttribute = null;
3962
                ReleaseCOMObjects(_LMSymbol);
3963
                _LMSymbol = null;
3964
            }
3965

    
3966
            endList.Add(text);
3967
        }
3968

    
3969
        /// <summary>
3970
        /// Note Modeling
3971
        /// </summary>
3972
        /// <param name="note"></param>
3973
        private void NoteModeling(Note note, List<Note> correctList)
3974
        {
3975
            LMSymbol _LMSymbol = null;
3976
            LMItemNote _LMItemNote = null;
3977
            LMAAttribute _LMAAttribute = null;
3978

    
3979
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
3980
            {
3981
                double x = 0;
3982
                double y = 0;
3983

    
3984
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
3985
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
3986
                note.SPPID.SPPID_X = x;
3987
                note.SPPID.SPPID_Y = y;
3988

    
3989
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
3990
                if (_LMSymbol != null)
3991
                {
3992
                    _LMSymbol.Commit();
3993
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
3994
                    if (_LMItemNote != null)
3995
                    {
3996
                        _LMItemNote.Commit();
3997
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
3998
                        if (_LMAAttribute != null)
3999
                        {
4000
                            _LMAAttribute.set_Value(note.VALUE);
4001
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4002

    
4003
                            double[] range = null;
4004
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4005
                            {
4006
                                double[] temp = null;
4007
                                GetSPPIDSymbolRange(labelPersist, ref temp);
4008
                                if (temp != null)
4009
                                {
4010
                                    if (range == null)
4011
                                        range = temp;
4012
                                    else
4013
                                    {
4014
                                        range = new double[] {
4015
                                            Math.Min(range[0], temp[0]),
4016
                                            Math.Min(range[1], temp[1]),
4017
                                            Math.Max(range[2], temp[2]),
4018
                                            Math.Max(range[3], temp[3])
4019
                                        };
4020
                                    }
4021
                                }
4022
                            }
4023
                            if (range != null)
4024
                                correctList.Add(note);
4025
                            note.SPPID.Range = range;
4026

    
4027

    
4028
                            _LMItemNote.Commit();
4029
                        }
4030
                    }
4031
                }
4032
            }
4033

    
4034
            if (_LMAAttribute != null)
4035
                ReleaseCOMObjects(_LMAAttribute);
4036
            if (_LMItemNote != null)
4037
                ReleaseCOMObjects(_LMItemNote);
4038
            if (_LMSymbol != null)
4039
                ReleaseCOMObjects(_LMSymbol);
4040
        }
4041

    
4042
        private void NoteCorrectModeling(Note note, List<Note> endList)
4043
        {
4044
            bool needRemodeling = false;
4045
            bool loop = true;
4046
            GridSetting gridSetting = GridSetting.GetInstance();
4047
            while (loop)
4048
            {
4049
                loop = false;
4050
                foreach (var overlap in endList)
4051
                {
4052
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
4053
                    {
4054
                        double tempX = 0;
4055
                        double tempY = 0;
4056
                        bool overlapX = false;
4057
                        bool overlapY = false;
4058
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4059
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
4060
                        if (overlapY && angle >= 45)
4061
                        {
4062
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4063
                            double move = gridSetting.Length * count;
4064
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
4065
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
4066
                            needRemodeling = true;
4067
                            loop = true;
4068
                        }
4069
                        if (overlapX && angle <= 45)
4070
                        {
4071
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4072
                            double move = gridSetting.Length * count;
4073
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
4074
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
4075
                            needRemodeling = true;
4076
                            loop = true;
4077
                        }
4078
                    }
4079
                }
4080
            }
4081

    
4082

    
4083
            if (needRemodeling)
4084
            {
4085
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
4086
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4087
                note.SPPID.RepresentationId = null;
4088

    
4089
                LMItemNote _LMItemNote = null;
4090
                LMAAttribute _LMAAttribute = null;
4091
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
4092
                if (_LMSymbol != null)
4093
                {
4094
                    _LMSymbol.Commit();
4095
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4096
                    if (_LMItemNote != null)
4097
                    {
4098
                        _LMItemNote.Commit();
4099
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4100
                        if (_LMAAttribute != null)
4101
                        {
4102
                            _LMAAttribute.set_Value(note.VALUE);
4103
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4104
                            _LMItemNote.Commit();
4105

    
4106
                            ReleaseCOMObjects(_LMAAttribute);
4107
                            ReleaseCOMObjects(_LMItemNote);
4108
                        }
4109
                    }
4110
                }
4111

    
4112
                ReleaseCOMObjects(symbol);
4113
                symbol = null;
4114
                ReleaseCOMObjects(_LMItemNote);
4115
                _LMItemNote = null;
4116
                ReleaseCOMObjects(_LMAAttribute);
4117
                _LMAAttribute = null;
4118
                ReleaseCOMObjects(_LMSymbol);
4119
                _LMSymbol = null;
4120
            }
4121

    
4122
            endList.Add(note);
4123
        }
4124

    
4125
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
4126
        {
4127
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4128
            if (modelItem != null)
4129
            {
4130
                foreach (LMRepresentation rep in modelItem.Representations)
4131
                {
4132
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4133
                    {
4134
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4135
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4136
                        {
4137
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
4138
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
4139
                            if (modelItemIds.Count == 1)
4140
                            {
4141
                                string joinModelItemId = modelItemIds[0];
4142
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
4143
                                if (survivorId != null)
4144
                                    break;
4145
                            }
4146
                        }
4147
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4148
                        {
4149
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
4150
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
4151
                            if (modelItemIds.Count == 1)
4152
                            {
4153
                                string joinModelItemId = modelItemIds[0];
4154
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
4155
                                if (survivorId != null)
4156
                                    break;
4157
                            }
4158
                        }
4159
                    }
4160
                }
4161
            }
4162
        }
4163

    
4164
        /// <summary>
4165
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
4166
        /// </summary>
4167
        /// <param name="x"></param>
4168
        /// <param name="y"></param>
4169
        /// <param name="originX"></param>
4170
        /// <param name="originY"></param>
4171
        /// <param name="SPPIDLabelLocation"></param>
4172
        /// <param name="location"></param>
4173
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
4174
        {
4175
            if (location == Location.None)
4176
            {
4177
                x = originX;
4178
                y = originY;
4179
            }
4180
            else
4181
            {
4182
                if (location.HasFlag(Location.Center))
4183
                {
4184
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
4185
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
4186
                }
4187

    
4188
                if (location.HasFlag(Location.Left))
4189
                    x = SPPIDLabelLocation.X1;
4190
                else if (location.HasFlag(Location.Right))
4191
                    x = SPPIDLabelLocation.X2;
4192

    
4193
                if (location.HasFlag(Location.Down))
4194
                    y = SPPIDLabelLocation.Y1;
4195
                else if (location.HasFlag(Location.Up))
4196
                    y = SPPIDLabelLocation.Y2;
4197
            }
4198
        }
4199

    
4200
        /// <summary>
4201
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
4202
        /// 1. Angle Valve
4203
        /// 2. 3개로 이루어진 Symbol Group
4204
        /// </summary>
4205
        /// <returns></returns>
4206
        private List<Symbol> GetPrioritySymbol()
4207
        {
4208
            DataTable symbolTable = document.SymbolTable;
4209
            // List에 순서대로 쌓는다.
4210
            List<Symbol> symbols = new List<Symbol>();
4211

    
4212
            // Angle Valve 부터
4213
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
4214
            {
4215
                if (!symbols.Contains(symbol))
4216
                {
4217
                    double originX = 0;
4218
                    double originY = 0;
4219

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

    
4224
                    SlopeType slopeType1 = SlopeType.None;
4225
                    SlopeType slopeType2 = SlopeType.None;
4226
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
4227
                    {
4228
                        double connectorX = 0;
4229
                        double connectorY = 0;
4230
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
4231
                        if (slopeType1 == SlopeType.None)
4232
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
4233
                        else
4234
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
4235
                    }
4236

    
4237
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
4238
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
4239
                        symbols.Add(symbol);
4240
                }
4241
            }
4242

    
4243
            List<Symbol> tempSymbols = new List<Symbol>();
4244
            // Conn 갯수 기준
4245
            foreach (var item in document.SYMBOLS)
4246
            {
4247
                if (!symbols.Contains(item))
4248
                    tempSymbols.Add(item);
4249
            }
4250
            tempSymbols.Sort(SortSymbolPriority);
4251
            symbols.AddRange(tempSymbols);
4252

    
4253
            return symbols;
4254
        }
4255

    
4256
        private void SetPriorityLine(List<Line> lines)
4257
        {
4258
            lines.Sort(SortLinePriority);
4259

    
4260
            int SortLinePriority(Line a, Line b)
4261
            {
4262
                // Branch 없는것부터
4263
                int branchRetval = CompareBranchLine(a, b);
4264
                if (branchRetval != 0)
4265
                {
4266
                    return branchRetval;
4267
                }
4268
                else
4269
                {
4270
                    // Symbol 연결 갯수
4271
                    int connSymbolRetval = CompareConnSymbol(a, b);
4272
                    if (connSymbolRetval != 0)
4273
                    {
4274
                        return connSymbolRetval;
4275
                    }
4276
                    else
4277
                    {
4278
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
4279
                        int connItemRetval = CompareConnItem(a, b);
4280
                        if (connItemRetval != 0)
4281
                        {
4282
                            return connItemRetval;
4283
                        }
4284
                        else
4285
                        {
4286
                            // ConnectedItem이 없는것
4287
                            int noneConnRetval = CompareNoneConn(a, b);
4288
                            if (noneConnRetval != 0)
4289
                            {
4290
                                return noneConnRetval;
4291
                            }
4292
                            else
4293
                            {
4294

    
4295
                            }
4296
                        }
4297
                    }
4298
                }
4299

    
4300
                return 0;
4301
            }
4302

    
4303
            int CompareNotSegmentLine(Line a, Line b)
4304
            {
4305
                List<Connector> connectorsA = a.CONNECTORS
4306
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4307
                    .ToList();
4308

    
4309
                List<Connector> connectorsB = b.CONNECTORS
4310
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4311
                    .ToList();
4312

    
4313
                // 오름차순
4314
                return connectorsB.Count.CompareTo(connectorsA.Count);
4315
            }
4316

    
4317
            int CompareConnSymbol(Line a, Line b)
4318
            {
4319
                List<Connector> connectorsA = a.CONNECTORS
4320
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4321
                    .ToList();
4322

    
4323
                List<Connector> connectorsB = b.CONNECTORS
4324
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4325
                    .ToList();
4326

    
4327
                // 오름차순
4328
                return connectorsB.Count.CompareTo(connectorsA.Count);
4329
            }
4330

    
4331
            int CompareConnItem(Line a, Line b)
4332
            {
4333
                List<Connector> connectorsA = a.CONNECTORS
4334
                    .Where(conn => conn.ConnectedObject != null && 
4335
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
4336
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
4337
                    .ToList();
4338

    
4339
                List<Connector> connectorsB = b.CONNECTORS
4340
                    .Where(conn => conn.ConnectedObject != null &&
4341
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
4342
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
4343
                    .ToList();
4344

    
4345
                // 오름차순
4346
                return connectorsB.Count.CompareTo(connectorsA.Count);
4347
            }
4348

    
4349
            int CompareBranchLine(Line a, Line b)
4350
            {
4351
                List<Connector> connectorsA = a.CONNECTORS
4352
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
4353
                    .ToList();
4354
                List<Connector> connectorsB = b.CONNECTORS
4355
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
4356
                    .ToList();
4357

    
4358
                // 내림차순
4359
                return connectorsA.Count.CompareTo(connectorsB.Count);
4360
            }
4361

    
4362
            int CompareNoneConn(Line a, Line b)
4363
            {
4364
                List<Connector> connectorsA = a.CONNECTORS
4365
                    .Where(conn => conn.ConnectedObject == null)
4366
                    .ToList();
4367

    
4368
                List<Connector> connectorsB = b.CONNECTORS
4369
                    .Where(conn => conn.ConnectedObject == null)
4370
                    .ToList();
4371

    
4372
                // 오름차순
4373
                return connectorsB.Count.CompareTo(connectorsA.Count);
4374
            }
4375
        }
4376

    
4377
        private void SortText(List<Text> texts)
4378
        {
4379
            texts.Sort(Sort);
4380

    
4381
            int Sort(Text a, Text b)
4382
            {
4383
                int yRetval = CompareY(a, b);
4384
                if (yRetval != 0)
4385
                {
4386
                    return yRetval;
4387
                }
4388
                else
4389
                {
4390
                    return CompareX(a, b);
4391
                }
4392
            }
4393

    
4394
            int CompareY(Text a, Text b)
4395
            {
4396
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
4397
            }
4398

    
4399
            int CompareX(Text a, Text b)
4400
            {
4401
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
4402
            }
4403
        }
4404
        private void SortNote(List<Note> notes)
4405
        {
4406
            notes.Sort(Sort);
4407

    
4408
            int Sort(Note a, Note b)
4409
            {
4410
                int yRetval = CompareY(a, b);
4411
                if (yRetval != 0)
4412
                {
4413
                    return yRetval;
4414
                }
4415
                else
4416
                {
4417
                    return CompareX(a, b);
4418
                }
4419
            }
4420

    
4421
            int CompareY(Note a, Note b)
4422
            {
4423
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
4424
            }
4425

    
4426
            int CompareX(Note a, Note b)
4427
            {
4428
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
4429
            }
4430
        }
4431

    
4432
        private void SortBranchLines()
4433
        {
4434
            BranchLines.Sort(SortBranchLine);
4435
            int SortBranchLine(Line a, Line b)
4436
            {
4437
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4438
                 x.ConnectedObject.GetType() == typeof(Line) &&
4439
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
4440
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4441

    
4442
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4443
                 x.ConnectedObject.GetType() == typeof(Line) &&
4444
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
4445
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4446

    
4447
                // 내림차순
4448
                return countA.CompareTo(countB);
4449
            }
4450
        }
4451

    
4452
        private static int SortSymbolPriority(Symbol a, Symbol b)
4453
        {
4454
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4455
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
4456
            int retval = countB.CompareTo(countA);
4457
            if (retval != 0)
4458
                return retval;
4459
            else
4460
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
4461
        }
4462

    
4463
        private string GetSPPIDFileName(LMModelItem modelItem)
4464
        {
4465
            string symbolPath = null;
4466
            foreach (LMRepresentation rep in modelItem.Representations)
4467
            {
4468
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4469
                {
4470
                    symbolPath = rep.get_FileName();
4471
                    break;
4472
                }
4473
            }
4474
            return symbolPath;
4475
        }
4476

    
4477
        private string GetSPPIDFileName(string modelItemId)
4478
        {
4479
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4480
            string symbolPath = null;
4481
            foreach (LMRepresentation rep in modelItem.Representations)
4482
            {
4483
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
4484
                {
4485
                    symbolPath = rep.get_FileName();
4486
                    break;
4487
                }
4488
            }
4489
            ReleaseCOMObjects(modelItem);
4490
            return symbolPath;
4491
        }
4492

    
4493
        /// <summary>
4494
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
4495
        /// </summary>
4496
        /// <param name="graphicOID"></param>
4497
        /// <param name="milliseconds"></param>
4498
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
4499
        {
4500
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
4501
            {
4502
                double minX = 0;
4503
                double minY = 0;
4504
                double maxX = 0;
4505
                double maxY = 0;
4506
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
4507
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
4508

    
4509
                Thread.Sleep(milliseconds);
4510
            }
4511
        }
4512

    
4513
        /// <summary>
4514
        /// ComObject를 Release
4515
        /// </summary>
4516
        /// <param name="objVars"></param>
4517
        public void ReleaseCOMObjects(params object[] objVars)
4518
        {
4519
            if (objVars != null)
4520
            {
4521
                int intNewRefCount = 0;
4522
                foreach (object obj in objVars)
4523
                {
4524
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
4525
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
4526
                }
4527
            }
4528
        }
4529

    
4530
        /// IDisposable 구현
4531
        ~AutoModeling()
4532
        {
4533
            this.Dispose(false);
4534
        }
4535

    
4536
        private bool disposed;
4537
        public void Dispose()
4538
        {
4539
            this.Dispose(true);
4540
            GC.SuppressFinalize(this);
4541
        }
4542

    
4543
        protected virtual void Dispose(bool disposing)
4544
        {
4545
            if (this.disposed) return;
4546
            if (disposing)
4547
            {
4548
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
4549
            }
4550
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
4551
            this.disposed = true;
4552
        }
4553
    }
4554
}
클립보드 이미지 추가 (최대 크기: 500 MB)