프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ f6761598

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

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

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

    
154
                Log.Write("End Modeling");
155
                radApp.ActiveWindow.Fit();
156

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

    
174
                ReleaseCOMObjects(dataSource);
175
                dataSource = null;
176
                ReleaseCOMObjects(_placement);
177
                _placement = null;
178

    
179
                Thread.Sleep(1000);
180
            }
181
        }
182

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

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

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

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

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

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

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

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

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

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

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

    
558
                    }
559
                }
560
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
561
            }
562

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

    
623
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
624

    
625
                        ReleaseCOMObjects(modelItem);
626
                        modelItem = null;
627
                    }
628
                }
629

    
630
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
631
            }
632
            foreach (var modelId in ZeroLengthModelItemID)
633
            {
634
                LMModelItem zeroLengthModelItem = dataSource.GetModelItem(modelId);
635
                LMAAttribute attribute = zeroLengthModelItem.Attributes["FlowDirection"];
636
                if (attribute != null && zeroLengthModelItem.get_ItemStatus() == "Active")
637
                {
638
                    attribute.set_Value("End 1 is upstream (Inlet)");
639
                    zeroLengthModelItem.Commit();
640
                }
641

    
642
                SetFlowDirectionByLine(modelId);
643

    
644
                ReleaseCOMObjects(zeroLengthModelItem);
645
                zeroLengthModelItem = null;
646

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

    
659
                SetFlowDirectionByLine(modelId);
660

    
661
                ReleaseCOMObjects(zeroLengthModelItem);
662
                zeroLengthModelItem = null;
663

    
664
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
665
            }
666
            foreach (var modelId in ZeroLengthSymbolToSymbolModelItemID)
667
            {
668
                SetFlowDirectionByLine(modelId);
669
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
670
            }
671

    
672
            void SetFlowDirectionByLine(string lineModelItemID)
673
            {
674
                LMModelItem modelItem = dataSource.GetModelItem(lineModelItemID);
675
                if (modelItem != null && modelItem.get_ItemStatus() == "Active")
676
                {
677
                    LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
678
                    if (attribute != null && !DBNull.Value.Equals(attribute.get_Value()))
679
                    {
680
                        string sFlowDirection = attribute.get_Value().ToString();
681
                        foreach (LMRepresentation rep in modelItem.Representations)
682
                        {
683
                            if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
684
                            {
685
                                LMConnector connector = dataSource.GetConnector(rep.Id);
686

    
687
                                foreach (LMRelationship relationship in connector.Relation1Relationships)
688
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
689
                                foreach (LMRelationship relationship in connector.Relation2Relationships)
690
                                    SetSymbolFlowDirectionByRelationShip(relationship, connector, sFlowDirection);
691

    
692
                                ReleaseCOMObjects(connector);
693
                            }
694
                        }
695
                    }
696
                    ReleaseCOMObjects(modelItem);
697
                    modelItem = null;
698
                }
699

    
700
                void SetSymbolFlowDirectionByRelationShip(LMRelationship relationship, LMConnector connector, string sFlowDirection)
701
                {
702
                    // Item2가 Symbol
703
                    if (!DBNull.Value.Equals(relationship.Item1RepresentationID) && relationship.Item1RepresentationID == connector.Id &&
704
                        relationship.Item2RepresentationObject != null && relationship.Item2RepresentationObject.get_RepresentationType() == "Symbol")
705
                    {
706
                        int symbolIndex = Convert.ToInt32(relationship.get_Item2Location());
707
                        int lineIndex = Convert.ToInt32(relationship.get_Item1Location());
708
                        LMModelItem symbolModelItem = relationship.Item2RepresentationObject.ModelItemObject;
709

    
710
                        SetSymbolFlowDirection(lineIndex, symbolIndex, sFlowDirection, symbolModelItem);
711

    
712
                        symbolModelItem.Commit();
713
                        ReleaseCOMObjects(symbolModelItem);
714
                        symbolModelItem = null;
715
                    }
716
                    // Item1이 Symbol
717
                    else if (!DBNull.Value.Equals(relationship.Item2RepresentationID) && relationship.Item2RepresentationID == connector.Id &&
718
                            relationship.Item1RepresentationObject != null && relationship.Item1RepresentationObject.get_RepresentationType() == "Symbol")
719
                    {
720
                        int symbolIndex = Convert.ToInt32(relationship.get_Item1Location());
721
                        int lineIndex = Convert.ToInt32(relationship.get_Item2Location());
722
                        LMModelItem symbolModelItem = relationship.Item1RepresentationObject.ModelItemObject;
723

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

    
726
                        symbolModelItem.Commit();
727
                        ReleaseCOMObjects(symbolModelItem);
728
                        symbolModelItem = null;
729
                    }
730
                }
731

    
732
                void SetSymbolFlowDirection(int lineIndex, int symbolIndex, string sFlowDirection, LMModelItem symbolModelItem)
733
                {
734
                    string attrName = "PipingPoint" + symbolIndex + ".FlowDirection";
735
                    LMAAttribute attribute = symbolModelItem.Attributes[attrName];
736
                    if (attribute != null)
737
                    {
738
                        if (lineIndex == 0 && sFlowDirection == "End 1 is upstream (Inlet)")
739
                            attribute.set_Value("End 1 is downstream (Outlet)");
740
                        else if (lineIndex == 0 && sFlowDirection == "End 1 is downstream (Outlet)")
741
                            attribute.set_Value("End 1 is upstream (Inlet)");
742
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is upstream (Inlet)")
743
                            attribute.set_Value("End 1 is upstream (Inlet)");
744
                        else if (lineIndex == 1 && sFlowDirection == "End 1 is downstream (Outlet)")
745
                            attribute.set_Value("End 1 is downstream (Outlet)");
746
                    }
747
                }
748
            }
749
        }
750
        private void RunNoteModeling()
751
        {
752
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
753
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
754
            List<Note> correctList = new List<Note>();
755
            foreach (var item in document.NOTES)
756
                try
757
                {
758
                    NoteModeling(item, correctList);
759
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
760
                }
761
                catch (Exception ex)
762
                {
763
                    Log.Write("Error in NoteModeling");
764
                    Log.Write("UID : " + item.UID);
765
                    Log.Write(ex.Message);
766
                    Log.Write(ex.StackTrace);
767
                }
768

    
769
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
770
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
771
            SortNote(correctList);
772
            List<Note> endList = new List<Note>();
773
            if (correctList.Count > 0)
774
                endList.Add(correctList[0]);
775
            foreach (var item in correctList)
776
                try
777
                {
778
                    if (!endList.Contains(item))
779
                        NoteCorrectModeling(item, endList);
780
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
781
                }
782
                catch (Exception ex)
783
                {
784
                    Log.Write("Error in NoteModeling");
785
                    Log.Write("UID : " + item.UID);
786
                    Log.Write(ex.Message);
787
                    Log.Write(ex.StackTrace);
788
                }
789
        }
790
        private void RunTextModeling()
791
        {
792
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
793
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
794
            List<Text> correctList = new List<Text>();
795
            foreach (var item in document.TEXTINFOS)
796
                try
797
                {
798
                    TextModeling(item, correctList);
799
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
800
                }
801
                catch (Exception ex)
802
                {
803
                    Log.Write("Error in TextModeling");
804
                    Log.Write("UID : " + item.UID);
805
                    Log.Write(ex.Message);
806
                    Log.Write(ex.StackTrace);
807
                }
808

    
809
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
810
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Text");
811
            SortText(correctList);
812
            List<Text> endList = new List<Text>();
813
            if (correctList.Count > 0)
814
                endList.Add(correctList[0]);
815
            foreach (var item in correctList)
816
                try
817
                {
818
                    if (!endList.Contains(item))
819
                        TextCorrectModeling(item, endList);
820
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
821
                }
822
                catch (Exception ex)
823
                {
824
                    Log.Write("Error in TextModeling");
825
                    Log.Write("UID : " + item.UID);
826
                    Log.Write(ex.Message);
827
                    Log.Write(ex.StackTrace);
828
                }
829
        }
830
        private void RunInputLineNumberAttribute()
831
        {
832
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
833
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
834
            List<string> endLine = new List<string>();
835
            foreach (var item in document.LINENUMBERS)
836
                try
837
                {
838
                    InputLineNumberAttribute(item, endLine);
839
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
840
                }
841
                catch (Exception ex)
842
                {
843
                    Log.Write("Error in InputLineNumberAttribute");
844
                    Log.Write("UID : " + item.UID);
845
                    Log.Write(ex.Message);
846
                    Log.Write(ex.StackTrace);
847
                }
848
        }
849
        private void RunInputSymbolAttribute()
850
        {
851
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
852
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
853
            foreach (var item in document.SYMBOLS)
854
                try
855
                {
856
                    InputSymbolAttribute(item, item.ATTRIBUTES);
857
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
858
                }
859
                catch (Exception ex)
860
                {
861
                    Log.Write("Error in InputSymbolAttribute");
862
                    Log.Write("UID : " + item.UID);
863
                    Log.Write(ex.Message);
864
                    Log.Write(ex.StackTrace);
865
                }
866
        }
867
        private void RunInputSpecBreakAttribute()
868
        {
869
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
870
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
871
            foreach (var item in document.SpecBreaks)
872
                try
873
                {
874
                    InputSpecBreakAttribute(item);
875
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
876
                }
877
                catch (Exception ex)
878
                {
879
                    Log.Write("Error in InputSpecBreakAttribute");
880
                    Log.Write("UID : " + item.UID);
881
                    Log.Write(ex.Message);
882
                    Log.Write(ex.StackTrace);
883
                }
884
        }
885
        private void RunLabelSymbolModeling()
886
        {
887
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
888
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
889
            foreach (var item in document.SYMBOLS)
890
                try
891
                {
892
                    LabelSymbolModeling(item);
893
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
894
                }
895
                catch (Exception ex)
896
                {
897
                    Log.Write("Error in LabelSymbolModeling");
898
                    Log.Write("UID : " + item.UID);
899
                    Log.Write(ex.Message);
900
                    Log.Write(ex.StackTrace);
901
                }
902
        }
903
        private void RunCorrectAssociationText()
904
        {
905
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
906
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Association Text");
907
            List<Text> endTexts = new List<Text>();
908
            foreach (var item in document.TEXTINFOS)
909
            {
910
                try
911
                {
912
                    if (item.ASSOCIATION && !endTexts.Contains(item))
913
                        AssociationTextCorrectModeling(item, endTexts);
914
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
915
                }
916
                catch (Exception ex)
917
                {
918
                    Log.Write("Error in NoteModeling");
919
                    Log.Write("UID : " + item.UID);
920
                    Log.Write(ex.Message);
921
                    Log.Write(ex.StackTrace);
922
                }
923
                
924
            }
925
        }
926
        /// <summary>
927
        /// 도면 생성 메서드
928
        /// </summary>
929
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
930
        {
931
            Log.Write("------------------ Start create document ------------------");
932
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
933
            Log.Write("Drawing name : " + drawingName);
934
            Log.Write("Drawing number : " + drawingNumber);
935
            Thread.Sleep(1000);
936
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
937
            if (newDrawing != null)
938
            {
939
                document.SPPID_DrawingNumber = drawingNumber;
940
                document.SPPID_DrawingName = drawingName;
941
                Thread.Sleep(1000);
942
                radApp.ActiveWindow.Fit();
943
                Thread.Sleep(1000);
944
                radApp.ActiveWindow.Zoom = 2000;
945
                Thread.Sleep(2000);
946

    
947
                //current LMDrawing 가져오기
948
                LMAFilter filter = new LMAFilter();
949
                LMACriterion criterion = new LMACriterion();
950
                filter.ItemType = "Drawing";
951
                criterion.SourceAttributeName = "Name";
952
                criterion.Operator = "=";
953
                criterion.set_ValueAttribute(drawingName);
954
                filter.get_Criteria().Add(criterion);
955

    
956
                LMDrawings drawings = new LMDrawings();
957
                drawings.Collect(dataSource, Filter: filter);
958

    
959
                drawingID = ((dynamic)drawings).Nth(1).Id;
960
                ReleaseCOMObjects(filter);
961
                ReleaseCOMObjects(criterion);
962
                ReleaseCOMObjects(drawings);
963
                filter = null;
964
                criterion = null;
965
                drawings = null;
966
            }
967
            else
968
                Log.Write("Fail Create Drawing");
969

    
970
            if (newDrawing != null)
971
                return true;
972
            else
973
                return false;
974
        }
975

    
976
        /// <summary>
977
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
978
        /// </summary>
979
        /// <param name="drawingName"></param>
980
        /// <param name="drawingNumber"></param>
981
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
982
        {
983
            LMDrawings drawings = new LMDrawings();
984
            drawings.Collect(dataSource);
985

    
986
            List<string> drawingNameList = new List<string>();
987
            List<string> drawingNumberList = new List<string>();
988

    
989
            foreach (LMDrawing item in drawings)
990
            {
991
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
992
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
993
            }
994

    
995
            int nameLength = drawingName.Length;
996
            while (drawingNameList.Contains(drawingName))
997
            {
998
                if (nameLength == drawingName.Length)
999
                    drawingName += "-1";
1000
                else
1001
                {
1002
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1003
                    drawingName = drawingName.Substring(0, nameLength + 1);
1004
                    drawingName += ++index;
1005
                }
1006
            }
1007

    
1008
            int numberLength = drawingNumber.Length;
1009
            while (drawingNameList.Contains(drawingNumber))
1010
            {
1011
                if (numberLength == drawingNumber.Length)
1012
                    drawingNumber += "-1";
1013
                else
1014
                {
1015
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1016
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1017
                    drawingNumber += ++index;
1018
                }
1019
            }
1020
            ReleaseCOMObjects(drawings);
1021
            drawings = null;
1022
        }
1023

    
1024
        /// <summary>
1025
        /// 도면 크기 구하는 메서드
1026
        /// </summary>
1027
        /// <returns></returns>
1028
        private bool DocumentCoordinateCorrection()
1029
        {
1030
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1031
            {
1032
                Log.Write("Setting Drawing X, Drawing Y");
1033
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1034
                Log.Write("Start coordinate correction");
1035
                document.CoordinateCorrection();
1036
                return true;
1037
            }
1038
            else
1039
            {
1040
                Log.Write("Need Drawing X, Y");
1041
                return false;
1042
            }
1043
        }
1044

    
1045
        /// <summary>
1046
        /// 심볼을 실제로 Modeling 메서드
1047
        /// </summary>
1048
        /// <param name="symbol">생성할 심볼</param>
1049
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1050
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1051
        {
1052
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1053
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1054
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1055
                return;
1056
            // 이미 모델링 됐을 경우
1057
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1058
                return;
1059

    
1060
            LMSymbol _LMSymbol = null;
1061

    
1062
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1063
            double x = symbol.SPPID.ORIGINAL_X;
1064
            double y = symbol.SPPID.ORIGINAL_Y;
1065
            int mirror = 0;
1066
            double angle = symbol.ANGLE;
1067

    
1068
            // OPC 일경우 180도 일때 Mirror
1069
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1070
                mirror = 1;
1071

    
1072
            // Mirror 계산
1073
            if (symbol.FLIP == 1)
1074
            {
1075
                mirror = 1;
1076
                angle += Math.PI;
1077
            }
1078

    
1079
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1080
            {
1081
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1082
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1083
                if (connector != null)
1084
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1085

    
1086
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1087
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1088
                if (temp != null)
1089
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1090
                ReleaseCOMObjects(temp);
1091
                temp = null;
1092

    
1093
                if (_LMSymbol != null && _TargetItem != null)
1094
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1095

    
1096
                ReleaseCOMObjects(_TargetItem);
1097
            }
1098
            else
1099
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1100

    
1101
            if (_LMSymbol != null)
1102
            {
1103
                _LMSymbol.Commit();
1104

    
1105
                // ConnCheck
1106
                List<string> ids = new List<string>();
1107
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1108
                {
1109
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1110
                        ids.Add(item.Id);
1111
                    ReleaseCOMObjects(item);
1112
                }
1113
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1114
                {
1115
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1116
                        ids.Add(item.Id);
1117
                    ReleaseCOMObjects(item);
1118
                }
1119

    
1120
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1121
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1122
                {
1123
                    double currentX = _LMSymbol.get_XCoordinate();
1124
                    double currentY = _LMSymbol.get_YCoordinate();
1125

    
1126

    
1127
                }
1128

    
1129
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1130
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1131
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1132

    
1133
                foreach (var item in symbol.ChildSymbols)
1134
                    CreateChildSymbol(item, _LMSymbol, symbol);
1135

    
1136
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1137
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1138

    
1139
                double[] range = null;
1140
                GetSPPIDSymbolRange(symbol, ref range);
1141
                symbol.SPPID.SPPID_Min_X = range[0];
1142
                symbol.SPPID.SPPID_Min_Y = range[1];
1143
                symbol.SPPID.SPPID_Max_X = range[2];
1144
                symbol.SPPID.SPPID_Max_Y = range[3];
1145

    
1146
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1147
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1148
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1149
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1150

    
1151
                ReleaseCOMObjects(_LMSymbol);
1152
            }
1153
        }
1154
        /// <summary>
1155
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1156
        /// Signal Point는 고려하지 않음
1157
        /// </summary>
1158
        /// <param name="symbol"></param>
1159
        /// <param name="_TargetItem"></param>
1160
        /// <param name="targetX"></param>
1161
        /// <param name="targetY"></param>
1162
        /// <returns></returns>
1163
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1164
        {
1165
            LMConnector tempConnector = null;
1166

    
1167
            List<Symbol> group = new List<Symbol>();
1168
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1169
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1170
            {
1171
                List<Connector> connectors = new List<Connector>();
1172
                foreach (var item in group)
1173
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1174
                /// Primary or Secondary Type Line만 고려
1175
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1176
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1177
                if (_connector != null)
1178
                {
1179
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1180
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1181
                    /// PipingPoint가 2개 이상만
1182
                    if (pointInfos.Count >= 2)
1183
                    {
1184
                        double lineX = 0;
1185
                        double lineY = 0;
1186
                        double length = 0;
1187
                        foreach (var item in pointInfos)
1188
                        {
1189
                            double tempX = item[1];
1190
                            double tempY = item[2];
1191

    
1192
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1193
                            if (calcDistance > length)
1194
                            {
1195
                                lineX = tempX;
1196
                                lineY = tempY;
1197
                            }
1198
                        }
1199

    
1200
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1201
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1202
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1203
                        placeRunInputs.AddPoint(-1, -1);
1204
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1205
                        if (tempConnector != null)
1206
                            tempConnector.Commit();
1207
                        ReleaseCOMObjects(_LMAItem);
1208
                        _LMAItem = null;
1209
                        ReleaseCOMObjects(placeRunInputs);
1210
                        placeRunInputs = null;
1211
                    }
1212
                }
1213
            }
1214

    
1215
            return tempConnector;
1216
        }
1217
        /// <summary>
1218
        /// Symbol의 PipingPoints를 구함
1219
        /// SignalPoint는 고려하지 않음
1220
        /// </summary>
1221
        /// <param name="symbol"></param>
1222
        /// <returns></returns>
1223
        private List<double[]> getPipingPoints(LMSymbol symbol)
1224
        {
1225
            LMModelItem modelItem = symbol.ModelItemObject;
1226
            LMPipingPoints pipingPoints = null;
1227
            if (modelItem.get_ItemTypeName() == "PipingComp")
1228
            {
1229
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1230
                pipingPoints = pipingComp.PipingPoints;
1231
                ReleaseCOMObjects(pipingComp);
1232
                pipingComp = null;
1233
            }
1234
            else if (modelItem.get_ItemTypeName() == "Instrument")
1235
            {
1236
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1237
                pipingPoints = instrument.PipingPoints;
1238
                ReleaseCOMObjects(instrument);
1239
                instrument = null;
1240
            }
1241
            else
1242
                Log.Write("다른 Type");
1243

    
1244
            List<double[]> info = new List<double[]>();
1245
            if (pipingPoints != null)
1246
            {
1247
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1248
                {
1249
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1250
                    {
1251
                        if (attribute.Name == "PipingPointNumber")
1252
                        {
1253
                            int index = Convert.ToInt32(attribute.get_Value());
1254
                            if (info.Find(loopX => loopX[0] == index) == null)
1255
                            {
1256
                                double x = 0;
1257
                                double y = 0;
1258
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1259
                                    info.Add(new double[] { index, x, y });
1260
                            }
1261
                        }
1262
                    }
1263
                }
1264
            }
1265
            ReleaseCOMObjects(modelItem);
1266
            modelItem = null;
1267
            ReleaseCOMObjects(pipingPoints);
1268
            pipingPoints = null;
1269

    
1270
            return info;
1271
        }
1272

    
1273
        private void RemoveSymbol(Symbol symbol)
1274
        {
1275
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1276
            {
1277
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1278
                if (_LMSymbol != null)
1279
                {
1280
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1281
                    ReleaseCOMObjects(_LMSymbol);
1282
                }
1283
            }
1284

    
1285
            symbol.SPPID.RepresentationId = string.Empty;
1286
            symbol.SPPID.ModelItemID = string.Empty;
1287
            symbol.SPPID.SPPID_X = double.NaN;
1288
            symbol.SPPID.SPPID_Y = double.NaN;
1289
            symbol.SPPID.SPPID_Min_X = double.NaN;
1290
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1291
            symbol.SPPID.SPPID_Max_X = double.NaN;
1292
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1293
        }
1294

    
1295
        private void RemoveSymbol(List<Symbol> symbols)
1296
        {
1297
            foreach (var symbol in symbols)
1298
            {
1299
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1300
                {
1301
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1302
                    if (_LMSymbol != null)
1303
                    {
1304
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1305
                        ReleaseCOMObjects(_LMSymbol);
1306
                    }
1307
                }
1308

    
1309
                symbol.SPPID.RepresentationId = string.Empty;
1310
                symbol.SPPID.ModelItemID = string.Empty;
1311
                symbol.SPPID.SPPID_X = double.NaN;
1312
                symbol.SPPID.SPPID_Y = double.NaN;
1313
                symbol.SPPID.SPPID_Min_X = double.NaN;
1314
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1315
                symbol.SPPID.SPPID_Max_X = double.NaN;
1316
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1317
            }
1318
        }
1319

    
1320
        /// <summary>
1321
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1322
        /// </summary>
1323
        /// <param name="targetConnector"></param>
1324
        /// <param name="targetSymbol"></param>
1325
        /// <param name="x"></param>
1326
        /// <param name="y"></param>
1327
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1328
        {
1329
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1330

    
1331
            double[] range = null;
1332
            List<double[]> points = new List<double[]>();
1333
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1334
            double x1 = range[0];
1335
            double y1 = range[1];
1336
            double x2 = range[2];
1337
            double y2 = range[3];
1338

    
1339
            // Origin 기준 Connector의 위치차이
1340
            double sceneX = 0;
1341
            double sceneY = 0;
1342
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1343
            double originX = 0;
1344
            double originY = 0;
1345
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1346
            double gapX = originX - sceneX;
1347
            double gapY = originY - sceneY;
1348

    
1349
            // SPPID Symbol과 ID2 심볼의 크기 차이
1350
            double sizeWidth = 0;
1351
            double sizeHeight = 0;
1352
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1353
            if (sizeWidth == 0 || sizeHeight == 0)
1354
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1355

    
1356
            double percentX = (x2 - x1) / sizeWidth;
1357
            double percentY = (y2 - y1) / sizeHeight;
1358

    
1359
            double SPPIDgapX = gapX * percentX;
1360
            double SPPIDgapY = gapY * percentY;
1361

    
1362
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1363
            double distance = double.MaxValue;
1364
            double[] resultPoint;
1365
            foreach (var point in points)
1366
            {
1367
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1368
                if (distance > result)
1369
                {
1370
                    distance = result;
1371
                    resultPoint = point;
1372
                    x = point[0];
1373
                    y = point[1];
1374
                }
1375
            }
1376

    
1377
            ReleaseCOMObjects(_TargetItem);
1378
        }
1379

    
1380
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1381
        {
1382
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1383
            if (index == 0)
1384
            {
1385
                x = targetLine.SPPID.START_X;
1386
                y = targetLine.SPPID.START_Y;
1387
            }
1388
            else
1389
            {
1390
                x = targetLine.SPPID.END_X;
1391
                y = targetLine.SPPID.END_Y;
1392
            }
1393
        }
1394

    
1395
        /// <summary>
1396
        /// SPPID Symbol의 Range를 구한다.
1397
        /// </summary>
1398
        /// <param name="symbol"></param>
1399
        /// <param name="range"></param>
1400
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1401
        {
1402
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1403
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1404
            double x1 = 0;
1405
            double y1 = 0;
1406
            double x2 = 0;
1407
            double y2 = 0;
1408
            symbol2d.Range(out x1, out y1, out x2, out y2);
1409
            range = new double[] { x1, y1, x2, y2 };
1410

    
1411
            for (int i = 1; i < int.MaxValue; i++)
1412
            {
1413
                double connX = 0;
1414
                double connY = 0;
1415
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1416
                    points.Add(new double[] { connX, connY });
1417
                else
1418
                    break;
1419
            }
1420

    
1421
            foreach (var childSymbol in symbol.ChildSymbols)
1422
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1423

    
1424
            ReleaseCOMObjects(_TargetItem);
1425
        }
1426

    
1427
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1428
        {
1429
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1430
            if (_TargetItem != null)
1431
            {
1432
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1433
                double x1 = 0;
1434
                double y1 = 0;
1435
                double x2 = 0;
1436
                double y2 = 0;
1437
                if (!bForGraphic)
1438
                {
1439
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1440
                    range = new double[] { x1, y1, x2, y2 };
1441
                }
1442
                else
1443
                {
1444
                    x1 = double.MaxValue;
1445
                    y1 = double.MaxValue;
1446
                    x2 = double.MinValue;
1447
                    y2 = double.MinValue;
1448
                    range = new double[] { x1, y1, x2, y2 };
1449

    
1450
                    foreach (var item in symbol2d.DrawingObjects)
1451
                    {
1452
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1453
                        {
1454
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1455
                            if (rangeObject.Layer == "Default")
1456
                            {
1457
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1458
                                range = new double[] {
1459
                                Math.Min(x1, range[0]),
1460
                                Math.Min(y1, range[1]),
1461
                                Math.Max(x2, range[2]),
1462
                                Math.Max(y2, range[3])
1463
                            };
1464
                            }
1465
                        }
1466
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1467
                        {
1468
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1469
                            if (rangeObject.Layer == "Default")
1470
                            {
1471
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1472
                                range = new double[] {
1473
                                Math.Min(x1, range[0]),
1474
                                Math.Min(y1, range[1]),
1475
                                Math.Max(x2, range[2]),
1476
                                Math.Max(y2, range[3])
1477
                            };
1478
                            }
1479
                        }
1480
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1481
                        {
1482
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1483
                            if (rangeObject.Layer == "Default")
1484
                            {
1485
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1486
                                range = new double[] {
1487
                                Math.Min(x1, range[0]),
1488
                                Math.Min(y1, range[1]),
1489
                                Math.Max(x2, range[2]),
1490
                                Math.Max(y2, range[3])
1491
                            };
1492
                            }
1493
                        }
1494
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1495
                        {
1496
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1497
                            if (rangeObject.Layer == "Default")
1498
                            {
1499
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1500
                                range = new double[] {
1501
                                Math.Min(x1, range[0]),
1502
                                Math.Min(y1, range[1]),
1503
                                Math.Max(x2, range[2]),
1504
                                Math.Max(y2, range[3])
1505
                            };
1506
                            }
1507
                        }
1508
                    }
1509
                }
1510

    
1511
                if (!bOnlySymbol)
1512
                {
1513
                    foreach (var childSymbol in symbol.ChildSymbols)
1514
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1515
                }
1516
                ReleaseCOMObjects(_TargetItem);
1517
            }
1518
        }
1519

    
1520
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1521
        {
1522
            if (labelPersist != null)
1523
            {
1524
                double x1 = double.MaxValue;
1525
                double y1 = double.MaxValue;
1526
                double x2 = double.MinValue;
1527
                double y2 = double.MinValue;
1528
                range = new double[] { x1, y1, x2, y2 };
1529

    
1530
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1531
                foreach (var item in dependency.DrawingObjects)
1532
                {
1533
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1534
                    if (textBox != null)
1535
                    {
1536
                        if (dependency != null)
1537
                        {
1538
                            double tempX1;
1539
                            double tempY1;
1540
                            double tempX2;
1541
                            double tempY2;
1542
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1543
                            x1 = Math.Min(x1, tempX1);
1544
                            y1 = Math.Min(y1, tempY1);
1545
                            x2 = Math.Max(x2, tempX2);
1546
                            y2 = Math.Max(y2, tempY2);
1547

    
1548
                            range = new double[] { x1, y1, x2, y2 };
1549
                        }
1550
                    }
1551
                }
1552
                
1553
            }
1554
        }
1555

    
1556
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1557
        {
1558
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1559
            foreach (var symbol in symbols)
1560
            {
1561
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1562
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1563
                double x1 = 0;
1564
                double y1 = 0;
1565
                double x2 = 0;
1566
                double y2 = 0;
1567
                symbol2d.Range(out x1, out y1, out x2, out y2);
1568

    
1569
                tempRange[0] = Math.Min(tempRange[0], x1);
1570
                tempRange[1] = Math.Min(tempRange[1], y1);
1571
                tempRange[2] = Math.Max(tempRange[2], x2);
1572
                tempRange[3] = Math.Max(tempRange[3], y2);
1573

    
1574
                foreach (var childSymbol in symbol.ChildSymbols)
1575
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1576

    
1577
                ReleaseCOMObjects(_TargetItem);
1578
            }
1579

    
1580
            range = tempRange;
1581
        }
1582

    
1583
        /// <summary>
1584
        /// Child Modeling 된 Symbol의 Range를 구한다.
1585
        /// </summary>
1586
        /// <param name="childSymbol"></param>
1587
        /// <param name="range"></param>
1588
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1589
        {
1590
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1591
            if (_ChildSymbol != null)
1592
            {
1593
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1594
                double x1 = 0;
1595
                double y1 = 0;
1596
                double x2 = 0;
1597
                double y2 = 0;
1598
                symbol2d.Range(out x1, out y1, out x2, out y2);
1599
                range[0] = Math.Min(range[0], x1);
1600
                range[1] = Math.Min(range[1], y1);
1601
                range[2] = Math.Max(range[2], x2);
1602
                range[3] = Math.Max(range[3], y2);
1603

    
1604
                for (int i = 1; i < int.MaxValue; i++)
1605
                {
1606
                    double connX = 0;
1607
                    double connY = 0;
1608
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1609
                        points.Add(new double[] { connX, connY });
1610
                    else
1611
                        break;
1612
                }
1613

    
1614
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1615
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1616

    
1617
                ReleaseCOMObjects(_ChildSymbol);
1618
            }
1619
        }
1620

    
1621
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1622
        {
1623
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1624
            if (_ChildSymbol != null)
1625
            {
1626
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1627
                double x1 = 0;
1628
                double y1 = 0;
1629
                double x2 = 0;
1630
                double y2 = 0;
1631
                symbol2d.Range(out x1, out y1, out x2, out y2);
1632
                range[0] = Math.Min(range[0], x1);
1633
                range[1] = Math.Min(range[1], y1);
1634
                range[2] = Math.Max(range[2], x2);
1635
                range[3] = Math.Max(range[3], y2);
1636

    
1637
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1638
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1639
                ReleaseCOMObjects(_ChildSymbol);
1640
            }
1641
        }
1642

    
1643
        /// <summary>
1644
        /// Label Symbol Modeling
1645
        /// </summary>
1646
        /// <param name="symbol"></param>
1647
        private void LabelSymbolModeling(Symbol symbol)
1648
        {
1649
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1650
            {
1651
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1652
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1653
                    return;
1654
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1655

    
1656
                string symbolUID = itemAttribute.VALUE;
1657
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1658
                if (targetItem != null &&
1659
                    (targetItem.GetType() == typeof(Symbol) ||
1660
                    targetItem.GetType() == typeof(Equipment)))
1661
                {
1662
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1663
                    string sRep = null;
1664
                    if (targetItem.GetType() == typeof(Symbol))
1665
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1666
                    else if (targetItem.GetType() == typeof(Equipment))
1667
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1668
                    if (!string.IsNullOrEmpty(sRep))
1669
                    {
1670
                        // LEADER Line 검사
1671
                        bool leaderLine = false;
1672
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1673
                        if (symbolMapping != null)
1674
                            leaderLine = symbolMapping.LEADERLINE;
1675

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

    
1680
                        //Leader 선 센터로
1681
                        if (_LMLabelPresist != null)
1682
                        {
1683
                            // Target Item에 Label의 Attribute Input
1684
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1685

    
1686
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1687
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1688
                            if (dependency != null)
1689
                            {
1690
                                bool result = false;
1691
                                foreach (var attributes in dependency.AttributeSets)
1692
                                {
1693
                                    foreach (var attribute in attributes)
1694
                                    {
1695
                                        string name = attribute.Name;
1696
                                        string value = attribute.GetValue().ToString();
1697
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1698
                                        {
1699
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1700
                                            {
1701
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1702
                                                {
1703
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1704
                                                    double prevX = _TargetItem.get_XCoordinate();
1705
                                                    double prevY = _TargetItem.get_YCoordinate();
1706
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1707
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1708
                                                    result = true;
1709
                                                    break;
1710
                                                }
1711
                                            }
1712
                                        }
1713

    
1714
                                        if (result)
1715
                                            break;
1716
                                    }
1717

    
1718
                                    if (result)
1719
                                        break;
1720
                                }
1721
                            }
1722

    
1723
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1724
                            _LMLabelPresist.Commit();
1725
                            ReleaseCOMObjects(_LMLabelPresist);
1726
                        }
1727

    
1728
                        ReleaseCOMObjects(_TargetItem);
1729
                    }
1730
                }
1731
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1732
                {
1733
                    Line targetLine = targetItem as Line;
1734
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1735
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1736
                    if (connectedLMConnector != null)
1737
                    {
1738
                        // LEADER Line 검사
1739
                        bool leaderLine = false;
1740
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1741
                        if (symbolMapping != null)
1742
                            leaderLine = symbolMapping.LEADERLINE;
1743

    
1744
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1745
                        if (_LMLabelPresist != null)
1746
                        {
1747
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1748
                            _LMLabelPresist.Commit();
1749
                            ReleaseCOMObjects(_LMLabelPresist);
1750
                        }
1751
                        ReleaseCOMObjects(connectedLMConnector);
1752
                    }
1753

    
1754
                    foreach (var item in connectorVertices)
1755
                        if (item.Key != null)
1756
                            ReleaseCOMObjects(item.Key);
1757
                }
1758
            }
1759
        }
1760

    
1761
        /// <summary>
1762
        /// Equipment를 실제로 Modeling 메서드
1763
        /// </summary>
1764
        /// <param name="equipment"></param>
1765
        private void EquipmentModeling(Equipment equipment)
1766
        {
1767
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1768
                return;
1769

    
1770
            LMSymbol _LMSymbol = null;
1771
            LMSymbol targetItem = null;
1772
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1773
            double x = equipment.SPPID.ORIGINAL_X;
1774
            double y = equipment.SPPID.ORIGINAL_Y;
1775
            int mirror = 0;
1776
            double angle = equipment.ANGLE;
1777

    
1778
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1779

    
1780
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1781
            if (connector != null)
1782
            {
1783
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1784
                if (connEquipment != null)
1785
                {
1786
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1787
                        EquipmentModeling(connEquipment);
1788

    
1789
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1790
                    {
1791
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1792
                        if (targetItem != null)
1793
                        {
1794
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1795
                        }
1796
                        else
1797
                        {
1798
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1799
                        }
1800
                    }
1801
                    else
1802
                    {
1803
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1804
                    }
1805
                }
1806
                else
1807
                {
1808
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1809
                }
1810
            }
1811
            else
1812
            {
1813
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1814
            }
1815

    
1816
            if (_LMSymbol != null)
1817
            {
1818
                _LMSymbol.Commit();
1819
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1820
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1821
                ReleaseCOMObjects(_LMSymbol);
1822
            }
1823

    
1824
            if (targetItem != null)
1825
            {
1826
                ReleaseCOMObjects(targetItem);
1827
            }
1828

    
1829
            ReleaseCOMObjects(_LMSymbol);
1830
        }
1831

    
1832
        /// <summary>
1833
        /// 첫 진입점
1834
        /// </summary>
1835
        /// <param name="symbol"></param>
1836
        private void SymbolModelingBySymbol(Symbol symbol)
1837
        {
1838
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1839
            List<object> endObjects = new List<object>();
1840
            endObjects.Add(symbol);
1841

    
1842
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1843
            foreach (var connector in symbol.CONNECTORS)
1844
            {
1845
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1846
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1847
                {
1848
                    endObjects.Add(connItem);
1849
                    if (connItem.GetType() == typeof(Symbol))
1850
                    {
1851
                        Symbol connSymbol = connItem as Symbol;
1852
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1853
                        {
1854
                            SymbolModeling(connSymbol, symbol);
1855
                        }
1856
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1857
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1858
                    }
1859
                    else if (connItem.GetType() == typeof(Line))
1860
                    {
1861
                        Line connLine = connItem as Line;
1862
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1863
                    }
1864
                }
1865
            }
1866
        }
1867

    
1868
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1869
        {
1870
            foreach (var connector in symbol.CONNECTORS)
1871
            {
1872
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1873
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1874
                {
1875
                    if (!endObjects.Contains(connItem))
1876
                    {
1877
                        endObjects.Add(connItem);
1878
                        if (connItem.GetType() == typeof(Symbol))
1879
                        {
1880
                            Symbol connSymbol = connItem as Symbol;
1881
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1882
                            {
1883
                                SymbolModeling(connSymbol, symbol);
1884
                            }
1885
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1886
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1887
                        }
1888
                        else if (connItem.GetType() == typeof(Line))
1889
                        {
1890
                            Line connLine = connItem as Line;
1891
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1892
                        }
1893
                    }
1894
                }
1895
            }
1896
        }
1897

    
1898
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
1899
        {
1900
            foreach (var connector in line.CONNECTORS)
1901
            {
1902
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1903
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1904
                {
1905
                    if (!endObjects.Contains(connItem))
1906
                    {
1907
                        endObjects.Add(connItem);
1908
                        if (connItem.GetType() == typeof(Symbol))
1909
                        {
1910
                            Symbol connSymbol = connItem as Symbol;
1911
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1912
                            {
1913
                                List<Symbol> group = new List<Symbol>();
1914
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
1915
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
1916
                                List<Symbol> endModelingGroup = new List<Symbol>();
1917
                                if (priority != null)
1918
                                {
1919
                                    SymbolGroupModeling(priority, group);
1920

    
1921
                                    // Range 겹치는지 확인해야함
1922
                                    double[] prevRange = null;
1923
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1924
                                    double[] groupRange = null;
1925
                                    GetSPPIDSymbolRange(group, ref groupRange);
1926

    
1927
                                    double distanceX = 0;
1928
                                    double distanceY = 0;
1929
                                    bool overlapX = false;
1930
                                    bool overlapY = false;
1931
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1932
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1933
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1934
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1935
                                    {
1936
                                        RemoveSymbol(group);
1937
                                        foreach (var _temp in group)
1938
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
1939

    
1940
                                        SymbolGroupModeling(priority, group);
1941
                                    }
1942
                                }
1943
                                else
1944
                                {
1945
                                    SymbolModeling(connSymbol, null);
1946
                                    // Range 겹치는지 확인해야함
1947
                                    double[] prevRange = null;
1948
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1949
                                    double[] connRange = null;
1950
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
1951

    
1952
                                    double distanceX = 0;
1953
                                    double distanceY = 0;
1954
                                    bool overlapX = false;
1955
                                    bool overlapY = false;
1956
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
1957
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
1958
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
1959
                                        (slopeType == SlopeType.VERTICAL && overlapY))
1960
                                    {
1961
                                        RemoveSymbol(connSymbol);
1962
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
1963

    
1964
                                        SymbolModeling(connSymbol, null);
1965
                                    }
1966
                                }
1967
                            }
1968
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1969
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1970
                        }
1971
                        else if (connItem.GetType() == typeof(Line))
1972
                        {
1973
                            Line connLine = connItem as Line;
1974
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
1975
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
1976
                        }
1977
                    }
1978
                }
1979
            }
1980
        }
1981

    
1982
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
1983
        {
1984
            List<Symbol> endModelingGroup = new List<Symbol>();
1985
            SymbolModeling(firstSymbol, null);
1986
            endModelingGroup.Add(firstSymbol);
1987
            while (endModelingGroup.Count != group.Count)
1988
            {
1989
                foreach (var _symbol in group)
1990
                {
1991
                    if (!endModelingGroup.Contains(_symbol))
1992
                    {
1993
                        foreach (var _connector in _symbol.CONNECTORS)
1994
                        {
1995
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
1996
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
1997
                            {
1998
                                SymbolModeling(_symbol, _connSymbol);
1999
                                endModelingGroup.Add(_symbol);
2000
                                break;
2001
                            }
2002
                        }
2003
                    }
2004
                }
2005
            }
2006
        }
2007

    
2008
        /// <summary>
2009
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2010
        /// </summary>
2011
        /// <param name="childSymbol"></param>
2012
        /// <param name="parentSymbol"></param>
2013
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2014
        {
2015
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2016
            double x1 = 0;
2017
            double x2 = 0;
2018
            double y1 = 0;
2019
            double y2 = 0;
2020
            symbol2d.Range(out x1, out y1, out x2, out y2);
2021

    
2022
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2023
            if (_LMSymbol != null)
2024
            {
2025
                _LMSymbol.Commit();
2026
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2027
                foreach (var item in childSymbol.ChildSymbols)
2028
                    CreateChildSymbol(item, _LMSymbol, parent);
2029
            }
2030

    
2031

    
2032
            ReleaseCOMObjects(_LMSymbol);
2033
        }
2034
        double index = 0;
2035
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2036
        {
2037
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2038
                return;
2039

    
2040
            List<Line> group = new List<Line>();
2041
            GetConnectedLineGroup(line, group);
2042
            LineCoordinateCorrection(group);
2043

    
2044
            foreach (var groupLine in group)
2045
            {
2046
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2047
                {
2048
                    BranchLines.Add(groupLine);
2049
                    continue;
2050
                }
2051

    
2052
                bool diagonal = false;
2053
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2054
                    diagonal = true;
2055
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2056
                LMSymbol _LMSymbolStart = null;
2057
                LMSymbol _LMSymbolEnd = null;
2058
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2059
                foreach (var connector in groupLine.CONNECTORS)
2060
                {
2061
                    double x = 0;
2062
                    double y = 0;
2063
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2064
                    if (connector.ConnectedObject == null)
2065
                    {
2066
                        placeRunInputs.AddPoint(x, y);
2067
                    }
2068
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2069
                    {
2070
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2071
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2072
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2073
                        {
2074
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2075
                            if (_LMSymbolStart != null)
2076
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2077
                            else
2078
                                placeRunInputs.AddPoint(x, y);
2079
                        }
2080
                        else
2081
                        {
2082
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2083
                            if (_LMSymbolEnd != null)
2084
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2085
                            else
2086
                                placeRunInputs.AddPoint(x, y);
2087
                        }
2088
                    }
2089
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2090
                    {
2091
                        Line targetLine = connector.ConnectedObject as Line;
2092
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2093
                        {
2094
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2095
                            if (targetConnector != null)
2096
                            {
2097
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2098
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2099
                            }
2100
                            else
2101
                            {
2102
                                placeRunInputs.AddPoint( x, y);
2103
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2104
                            }
2105
                        }
2106
                        else
2107
                        {
2108
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2109
                            {
2110
                                index += 0.01;
2111
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2112
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2113
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2114
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2115
                                else
2116
                                {
2117
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2118
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2119
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2120
                                    else
2121
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2122
                                }
2123
                            }
2124

    
2125
                            placeRunInputs.AddPoint(x, y);
2126

    
2127
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2128
                            {
2129
                                index += 0.01;
2130
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2131
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2132
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2133
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2134
                                else
2135
                                {
2136
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2137
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2138
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2139
                                    else
2140
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2141
                                }
2142
                            }
2143
                        }
2144
                    }
2145
                }
2146

    
2147
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2148
                if (_lMConnector != null)
2149
                {
2150
                    _lMConnector.Commit();
2151
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2152

    
2153
                    bool bRemodelingStart = false;
2154
                    if (_LMSymbolStart != null)
2155
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2156
                    bool bRemodelingEnd = false;
2157
                    if (_LMSymbolEnd != null)
2158
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2159

    
2160
                    if (bRemodelingStart || bRemodelingEnd)
2161
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2162

    
2163
                    FlowMarkModeling(groupLine);
2164
                    LineNumberModelingOnlyOne(groupLine);
2165

    
2166
                    ReleaseCOMObjects(_lMConnector);
2167
                }
2168
                else if (!isBranchModeling)
2169
                {
2170
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2171
                }
2172

    
2173
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2174
                x.ConnectedObject != null &&
2175
                x.ConnectedObject.GetType() == typeof(Line) &&
2176
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2177
                .Select(x => x.ConnectedObject)
2178
                .ToList();
2179

    
2180
                foreach (var item in removeLines)
2181
                    RemoveLineForModeling(item as Line);
2182

    
2183
                if (_LMAItem != null)
2184
                    ReleaseCOMObjects(_LMAItem);
2185
                if (placeRunInputs != null)
2186
                    ReleaseCOMObjects(placeRunInputs);
2187
                if (_LMSymbolStart != null)
2188
                    ReleaseCOMObjects(_LMSymbolStart);
2189
                if (_LMSymbolEnd != null)
2190
                    ReleaseCOMObjects(_LMSymbolEnd);
2191

    
2192
                if (isBranchModeling && BranchLines.Contains(groupLine))
2193
                    BranchLines.Remove(groupLine);
2194
            }
2195
        }
2196

    
2197
        private void RemoveLineForModeling(Line line)
2198
        {
2199
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2200
            if (modelItem != null)
2201
            {
2202
                foreach (LMRepresentation rep in modelItem.Representations)
2203
                {
2204
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2205
                    {
2206
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2207
                        dynamic OID = rep.get_GraphicOID().ToString();
2208
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2209
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2210
                        int verticesCount = lineStringGeometry.VertexCount;
2211
                        double[] vertices = null;
2212
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2213
                        for (int i = 0; i < verticesCount; i++)
2214
                        {
2215
                            double x = 0;
2216
                            double y = 0;
2217
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2218
                            if (verticesCount == 2 && (x < 0 || y < 0))
2219
                                _placement.PIDRemovePlacement(rep);
2220
                        }
2221
                        ReleaseCOMObjects(_LMConnector);
2222
                    }
2223
                }
2224

    
2225
                ReleaseCOMObjects(modelItem);
2226
            }
2227
        }
2228

    
2229
        private void GetConnectedLineGroup(Line line, List<Line> group)
2230
        {
2231
            if (!group.Contains(line))
2232
                group.Add(line);
2233
            foreach (var connector in line.CONNECTORS)
2234
            {
2235
                if (connector.ConnectedObject != null &&
2236
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2237
                    !group.Contains(connector.ConnectedObject) &&
2238
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2239
                {
2240
                    Line connLine = connector.ConnectedObject as Line;
2241
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2242
                    {
2243
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2244
                            group.Insert(0, connLine);
2245
                        else
2246
                            group.Add(connLine);
2247
                        GetConnectedLineGroup(connLine, group);
2248
                    }
2249
                }
2250
            }
2251
        }
2252

    
2253
        private void LineCoordinateCorrection(List<Line> group)
2254
        {
2255
            // 순서대로 전 Item 기준 정렬
2256
            LineCoordinateCorrectionByStart(group);
2257

    
2258
            // 역으로 심볼이 있을 경우 좌표 보정
2259
            LineCoordinateCorrectionForLastLine(group);
2260
        }
2261

    
2262
        private void LineCoordinateCorrectionByStart(List<Line> group)
2263
        {
2264
            for (int i = 0; i < group.Count; i++)
2265
            {
2266
                Line line = group[i];
2267
                if (i == 0)
2268
                {
2269
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2270
                    if (symbolConnector != null)
2271
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2272
                }
2273
                else if (i != 0)
2274
                {
2275
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2276
                }
2277
            }
2278
        }
2279

    
2280
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2281
        {
2282
            Line checkLine = group[group.Count - 1];
2283
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2284
            if (lastSymbolConnector != null)
2285
            {
2286
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2287
                for (int i = group.Count - 2; i >= 0; i--)
2288
                {
2289
                    Line line = group[i + 1];
2290
                    Line prevLine = group[i];
2291

    
2292
                    // 같으면 보정
2293
                    if (line.SlopeType == prevLine.SlopeType)
2294
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2295
                    else
2296
                    {
2297
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2298
                        {
2299
                            double prevX = 0;
2300
                            double prevY = 0;
2301
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2302
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2303

    
2304
                            double x = 0;
2305
                            double y = 0;
2306
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2307
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2308
                        }
2309
                        else if (line.SlopeType == SlopeType.VERTICAL)
2310
                        {
2311
                            double prevX = 0;
2312
                            double prevY = 0;
2313
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2314
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2315

    
2316
                            double x = 0;
2317
                            double y = 0;
2318
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2319
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2320
                        }
2321
                        break;
2322
                    }
2323
                }
2324
            }
2325
        }
2326

    
2327
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2328
        {
2329
            double x = 0;
2330
            double y = 0;
2331
            if (connItem.GetType() == typeof(Symbol))
2332
            {
2333
                Symbol targetSymbol = connItem as Symbol;
2334
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2335
                if (targetConnector != null)
2336
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2337
                else
2338
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2339
            }
2340
            else if (connItem.GetType() == typeof(Line))
2341
            {
2342
                Line targetLine = connItem as Line;
2343
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2344
            }
2345

    
2346
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2347
        }
2348

    
2349
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2350
        {
2351
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2352
            int index = line.CONNECTORS.IndexOf(connector);
2353
            if (index == 0)
2354
            {
2355
                line.SPPID.START_X = x;
2356
                line.SPPID.START_Y = y;
2357
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2358
                    line.SPPID.END_Y = y;
2359
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2360
                    line.SPPID.END_X = x;
2361
            }
2362
            else
2363
            {
2364
                line.SPPID.END_X = x;
2365
                line.SPPID.END_Y = y;
2366
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2367
                    line.SPPID.START_Y = y;
2368
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2369
                    line.SPPID.START_X = x;
2370
            }
2371
        }
2372

    
2373
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2374
        {
2375
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2376
            int index = line.CONNECTORS.IndexOf(connector);
2377
            if (index == 0)
2378
            {
2379
                line.SPPID.START_X = x;
2380
                if (line.SlopeType == SlopeType.VERTICAL)
2381
                    line.SPPID.END_X = x;
2382
            }
2383
            else
2384
            {
2385
                line.SPPID.END_X = x;
2386
                if (line.SlopeType == SlopeType.VERTICAL)
2387
                    line.SPPID.START_X = x;
2388
            }
2389
        }
2390

    
2391
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2392
        {
2393
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2394
            int index = line.CONNECTORS.IndexOf(connector);
2395
            if (index == 0)
2396
            {
2397
                line.SPPID.START_Y = y;
2398
                if (line.SlopeType == SlopeType.HORIZONTAL)
2399
                    line.SPPID.END_Y = y;
2400
            }
2401
            else
2402
            {
2403
                line.SPPID.END_Y = y;
2404
                if (line.SlopeType == SlopeType.HORIZONTAL)
2405
                    line.SPPID.START_Y = y;
2406
            }
2407
        }
2408

    
2409
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2410
        {
2411
            if (symbol != null)
2412
            {
2413
                string repID = symbol.AsLMRepresentation().Id;
2414
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2415
                string lineUID = line.UID;
2416

    
2417
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2418
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2419
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2420

    
2421
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2422
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2423
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2424

    
2425
                if (startSpecBreak != null || startEndBreak != null)
2426
                    result = true;
2427
            }
2428
        }
2429

    
2430
        /// <summary>
2431
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2432
        /// </summary>
2433
        /// <param name="lines"></param>
2434
        /// <param name="prevLMConnector"></param>
2435
        /// <param name="startSymbol"></param>
2436
        /// <param name="endSymbol"></param>
2437
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2438
        {
2439
            string symbolPath = string.Empty;
2440
            #region get symbol path
2441
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2442
            symbolPath = GetSPPIDFileName(modelItem);
2443
            ReleaseCOMObjects(modelItem);
2444
            #endregion
2445
            bool diagonal = false;
2446
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2447
                diagonal = true;
2448
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2449
            LMConnector newConnector = null;
2450
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2451
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2452
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2453
            int verticesCount = lineStringGeometry.VertexCount;
2454
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2455

    
2456
            List<double[]> vertices = new List<double[]>();
2457
            for (int i = 1; i <= verticesCount; i++)
2458
            {
2459
                double x = 0;
2460
                double y = 0;
2461
                lineStringGeometry.GetVertex(i, ref x, ref y);
2462
                vertices.Add(new double[] { x, y });
2463
            }
2464

    
2465
            for (int i = 0; i < vertices.Count; i++)
2466
            {
2467
                double[] points = vertices[i];
2468
                // 시작 심볼이 있고 첫번째 좌표일 때
2469
                if (startSymbol != null && i == 0)
2470
                {
2471
                    if (bStart)
2472
                    {
2473
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2474
                        if (slopeType == SlopeType.HORIZONTAL)
2475
                            placeRunInputs.AddPoint(points[0], -0.1);
2476
                        else if (slopeType == SlopeType.VERTICAL)
2477
                            placeRunInputs.AddPoint(-0.1, points[1]);
2478
                        else
2479
                            placeRunInputs.AddPoint(points[0], -0.1);
2480

    
2481
                        placeRunInputs.AddPoint(points[0], points[1]);
2482
                    }
2483
                    else
2484
                    {
2485
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2486
                    }
2487
                }
2488
                // 마지막 심볼이 있고 마지막 좌표일 때
2489
                else if (endSymbol != null && i == vertices.Count - 1)
2490
                {
2491
                    if (bEnd)
2492
                    {
2493
                        placeRunInputs.AddPoint(points[0], points[1]);
2494

    
2495
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2496
                        if (slopeType == SlopeType.HORIZONTAL)
2497
                            placeRunInputs.AddPoint(points[0], -0.1);
2498
                        else if (slopeType == SlopeType.VERTICAL)
2499
                            placeRunInputs.AddPoint(-0.1, points[1]);
2500
                        else
2501
                            placeRunInputs.AddPoint(points[0], -0.1);
2502
                    }
2503
                    else
2504
                    {
2505
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2506
                    }
2507
                }
2508
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2509
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2510
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2511
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2512
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2513
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2514
                else
2515
                    placeRunInputs.AddPoint(points[0], points[1]);
2516
            }
2517

    
2518
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2519
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2520

    
2521
            ReleaseCOMObjects(placeRunInputs);
2522
            ReleaseCOMObjects(_LMAItem);
2523
            ReleaseCOMObjects(modelItem);
2524

    
2525
            if (newConnector != null)
2526
            {
2527
                newConnector.Commit();
2528
                if (startSymbol != null && bStart)
2529
                {
2530
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2531
                    placeRunInputs = new PlaceRunInputs();
2532
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2533
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2534
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2535
                    if (_LMConnector != null)
2536
                    {
2537
                        _LMConnector.Commit();
2538
                        RemoveConnectorForReModelingLine(newConnector);
2539
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2540
                        ReleaseCOMObjects(_LMConnector);
2541
                    }
2542
                    ReleaseCOMObjects(placeRunInputs);
2543
                    ReleaseCOMObjects(_LMAItem);
2544
                }
2545

    
2546
                if (endSymbol != null && bEnd)
2547
                {
2548
                    if (startSymbol != null)
2549
                    {
2550
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2551
                        newConnector = dicVertices.First().Key;
2552
                    }
2553

    
2554
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2555
                    placeRunInputs = new PlaceRunInputs();
2556
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2557
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2558
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2559
                    if (_LMConnector != null)
2560
                    {
2561
                        _LMConnector.Commit();
2562
                        RemoveConnectorForReModelingLine(newConnector);
2563
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2564
                        ReleaseCOMObjects(_LMConnector);
2565
                    }
2566
                    ReleaseCOMObjects(placeRunInputs);
2567
                    ReleaseCOMObjects(_LMAItem);
2568
                }
2569

    
2570
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2571
                ReleaseCOMObjects(newConnector);
2572
            }
2573

    
2574
            ReleaseCOMObjects(modelItem);
2575
        }
2576

    
2577
        /// <summary>
2578
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2579
        /// </summary>
2580
        /// <param name="connector"></param>
2581
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2582
        {
2583
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2584
            foreach (var item in dicVertices)
2585
            {
2586
                if (item.Value.Count == 2)
2587
                {
2588
                    bool result = false;
2589
                    foreach (var point in item.Value)
2590
                    {
2591
                        if (point[0] < 0 || point[1] < 0)
2592
                        {
2593
                            result = true;
2594
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2595
                            break;
2596
                        }
2597
                    }
2598

    
2599
                    if (result)
2600
                        break;
2601
                }
2602
            }
2603
            foreach (var item in dicVertices)
2604
                ReleaseCOMObjects(item.Key);
2605
        }
2606

    
2607
        /// <summary>
2608
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2609
        /// </summary>
2610
        /// <param name="symbol"></param>
2611
        /// <param name="line"></param>
2612
        /// <returns></returns>
2613
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2614
        {
2615
            LMSymbol _LMSymbol = null;
2616
            foreach (var connector in symbol.CONNECTORS)
2617
            {
2618
                if (connector.CONNECTEDITEM == line.UID)
2619
                {
2620
                    if (connector.Index == 0)
2621
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2622
                    else
2623
                    {
2624
                        ChildSymbol child = null;
2625
                        foreach (var childSymbol in symbol.ChildSymbols)
2626
                        {
2627
                            if (childSymbol.Connectors.Contains(connector))
2628
                                child = childSymbol;
2629
                            else
2630
                                child = GetChildSymbolByConnector(childSymbol, connector);
2631

    
2632
                            if (child != null)
2633
                                break;
2634
                        }
2635

    
2636
                        if (child != null)
2637
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2638
                    }
2639

    
2640
                    break;
2641
                }
2642
            }
2643

    
2644
            return _LMSymbol;
2645
        }
2646

    
2647
        /// <summary>
2648
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2649
        /// </summary>
2650
        /// <param name="item"></param>
2651
        /// <param name="connector"></param>
2652
        /// <returns></returns>
2653
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2654
        {
2655
            foreach (var childSymbol in item.ChildSymbols)
2656
            {
2657
                if (childSymbol.Connectors.Contains(connector))
2658
                    return childSymbol;
2659
                else
2660
                    return GetChildSymbolByConnector(childSymbol, connector);
2661
            }
2662

    
2663
            return null;
2664
        }
2665

    
2666
        /// <summary>
2667
        /// EndBreak 모델링 메서드
2668
        /// </summary>
2669
        /// <param name="endBreak"></param>
2670
        private void EndBreakModeling(EndBreak endBreak)
2671
        {
2672
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2673
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2674

    
2675
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2676
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
2677
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2678

    
2679
            if (targetLMConnector != null)
2680
            {
2681
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2682
                Array array = null;
2683
                if (point != null)
2684
                    array = new double[] { 0, point[0], point[1] };
2685
                else
2686
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2687
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2688
                if (_LmLabelPersist != null)
2689
                {
2690
                    _LmLabelPersist.Commit();
2691
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2692
                    if (_LmLabelPersist.ModelItemObject != null)
2693
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2694
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2695
                    ReleaseCOMObjects(_LmLabelPersist);
2696
                }
2697
                ReleaseCOMObjects(targetLMConnector);
2698
            }
2699
            else
2700
            {
2701
                Log.Write("End Break UID : " + endBreak.UID);
2702
                Log.Write("Can't find targetLMConnector");
2703
            }
2704
        }
2705

    
2706
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
2707
        {
2708
            string symbolPath = string.Empty;
2709
            #region get symbol path
2710
            if (string.IsNullOrEmpty(changeSymbolPath))
2711
            {
2712
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2713
                symbolPath = GetSPPIDFileName(modelItem);
2714
                ReleaseCOMObjects(modelItem);
2715
            }
2716
            else
2717
                symbolPath = changeSymbolPath;
2718
            
2719
            #endregion
2720

    
2721
            LMConnector newConnector = null;
2722
            dynamic OID = connector.get_GraphicOID().ToString();
2723
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2724
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2725
            int verticesCount = lineStringGeometry.VertexCount;
2726
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2727
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2728

    
2729
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2730
            {
2731
                double[] vertices = null;
2732
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2733
                double x = 0;
2734
                double y = 0;
2735
                lineStringGeometry.GetVertex(1, ref x, ref y);
2736

    
2737
                string flowDirection = string.Empty;
2738
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2739
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2740
                    flowDirection = flowAttribute.get_Value().ToString();
2741

    
2742
                if (flowDirection == "End 1 is downstream (Outlet)")
2743
                {
2744
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2745
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2746
                    flowDirection = "End 1 is upstream (Inlet)";
2747
                }
2748
                else
2749
                {
2750
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
2751
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
2752
                }
2753
                string oldModelItemId = connector.ModelItemID;
2754
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2755
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2756
                newConnector.Commit();
2757
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
2758
                if (!string.IsNullOrEmpty(flowDirection))
2759
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
2760
                ReleaseCOMObjects(connector);
2761

    
2762
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
2763
                {
2764
                    foreach (var repId in line.SPPID.Representations)
2765
                    {
2766
                        LMConnector _connector = dataSource.GetConnector(repId);
2767
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
2768
                        {
2769
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
2770
                            {
2771
                                line.SPPID.ModelItemId = _connector.ModelItemID;
2772
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
2773
                            }
2774
                        }
2775
                        ReleaseCOMObjects(_connector);
2776
                        _connector = null;
2777
                    }
2778
                }
2779
            }
2780

    
2781
            return newConnector;
2782
        }
2783

    
2784
        /// <summary>
2785
        /// SpecBreak Modeling 메서드
2786
        /// </summary>
2787
        /// <param name="specBreak"></param>
2788
        private void SpecBreakModeling(SpecBreak specBreak)
2789
        {
2790
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
2791
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
2792

    
2793
            if (upStreamObj != null &&
2794
                downStreamObj != null)
2795
            {
2796
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2797
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && targetLMConnector != null)
2798
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2799

    
2800
                if (targetLMConnector != null)
2801
                {
2802
                    foreach (var attribute in specBreak.ATTRIBUTES)
2803
                    {
2804
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
2805
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
2806
                        {
2807
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
2808
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
2809
                            Array array = null;
2810
                            if (point != null)
2811
                                array = new double[] { 0, point[0], point[1] };
2812
                            else
2813
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
2814
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
2815

    
2816
                            if (_LmLabelPersist != null)
2817
                            {
2818
                                _LmLabelPersist.Commit();
2819
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2820
                                if (_LmLabelPersist.ModelItemObject != null)
2821
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2822
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2823
                                ReleaseCOMObjects(_LmLabelPersist);
2824
                            }
2825
                        }
2826
                    }
2827
                    ReleaseCOMObjects(targetLMConnector);
2828
                }
2829
                else
2830
                {
2831
                    Log.Write("Spec Break UID : " + specBreak.UID);
2832
                    Log.Write("Can't find targetLMConnector");
2833
                }
2834
            }
2835
        }
2836

    
2837
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
2838
        {
2839
            LMConnector targetConnector = null;
2840
            Symbol targetSymbol = targetObj as Symbol;
2841
            Symbol connectedSymbol = connectedObj as Symbol;
2842
            Line targetLine = targetObj as Line;
2843
            Line connectedLine = connectedObj as Line;
2844
            if (targetSymbol != null && connectedSymbol != null)
2845
            {
2846
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2847
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2848

    
2849
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2850
                {
2851
                    if (connector.get_ItemStatus() != "Active")
2852
                        continue;
2853

    
2854
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2855
                    {
2856
                        targetConnector = connector;
2857
                        break;
2858
                    }
2859
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2860
                    {
2861
                        targetConnector = connector;
2862
                        break;
2863
                    }
2864
                }
2865

    
2866
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2867
                {
2868
                    if (connector.get_ItemStatus() != "Active")
2869
                        continue;
2870

    
2871
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2872
                    {
2873
                        targetConnector = connector;
2874
                        break;
2875
                    }
2876
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2877
                    {
2878
                        targetConnector = connector;
2879
                        break;
2880
                    }
2881
                }
2882

    
2883
                ReleaseCOMObjects(targetLMSymbol);
2884
                ReleaseCOMObjects(connectedLMSymbol);
2885
            }
2886
            else if (targetLine != null && connectedLine != null)
2887
            {
2888
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2889
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2890

    
2891
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2892
                {
2893
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2894
                    {
2895
                        if (targetConnector != null)
2896
                            break;
2897

    
2898
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2899
                        {
2900
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2901

    
2902
                            if (IsConnected(_LMConnector, connectedModelItem))
2903
                                targetConnector = _LMConnector;
2904
                            else
2905
                                ReleaseCOMObjects(_LMConnector);
2906
                        }
2907
                    }
2908

    
2909
                    ReleaseCOMObjects(targetModelItem);
2910
                }
2911
            }
2912
            else
2913
            {
2914
                LMSymbol connectedLMSymbol = null;
2915
                if (connectedSymbol != null)
2916
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2917
                else if (targetSymbol != null)
2918
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2919
                else
2920
                {
2921

    
2922
                }
2923
                LMModelItem targetModelItem = null;
2924
                if (targetLine != null)
2925
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2926
                else if (connectedLine != null)
2927
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2928
                else
2929
                {
2930

    
2931
                }
2932
                if (connectedLMSymbol != null && targetModelItem != null)
2933
                {
2934
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2935
                    {
2936
                        if (connector.get_ItemStatus() != "Active")
2937
                            continue;
2938

    
2939
                        if (IsConnected(connector, targetModelItem))
2940
                        {
2941
                            targetConnector = connector;
2942
                            break;
2943
                        }
2944
                    }
2945

    
2946
                    if (targetConnector == null)
2947
                    {
2948
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2949
                        {
2950
                            if (connector.get_ItemStatus() != "Active")
2951
                                continue;
2952

    
2953
                            if (IsConnected(connector, targetModelItem))
2954
                            {
2955
                                targetConnector = connector;
2956
                                break;
2957
                            }
2958
                        }
2959
                    }
2960
                }
2961

    
2962
            }
2963

    
2964
            return targetConnector;
2965
        }
2966

    
2967
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
2968
        {
2969
            double[] result = null;
2970
            Line targetLine = targetObj as Line;
2971
            Symbol targetSymbol = targetObj as Symbol;
2972
            Line connLine = connObj as Line;
2973
            Symbol connSymbol = connObj as Symbol;
2974

    
2975
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
2976
            double lineMove = GridSetting.GetInstance().Length * 3;
2977
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
2978
            {
2979
                result = GetConnectorVertices(targetConnector)[0];
2980
                if (targetSymbol != null && connSymbol != null)
2981
                {
2982
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
2983
                    if (slopeType == SlopeType.HORIZONTAL)
2984
                        result = new double[] { result[0], result[1] - zeroLengthMove };
2985
                    else if (slopeType == SlopeType.VERTICAL)
2986
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
2987
                }
2988
                else if (targetLine != null)
2989
                {
2990
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
2991
                        result = new double[] { result[0], result[1] - zeroLengthMove };
2992
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
2993
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
2994
                }
2995
                else if (connLine != null)
2996
                {
2997
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
2998
                        result = new double[] { result[0], result[1] - zeroLengthMove };
2999
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3000
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3001
                }
3002
            }
3003
            else
3004
            {
3005
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3006
                {
3007
                    Line line = connObj as Line;
3008
                    LMConnector connectedConnector = null;
3009
                    int connIndex = 0;
3010
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3011
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3012

    
3013
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3014

    
3015
                    ReleaseCOMObjects(modelItem);
3016
                    ReleaseCOMObjects(connectedConnector);
3017

    
3018
                    if (vertices.Count > 0)
3019
                    {
3020
                        if (connIndex == 1)
3021
                            result = vertices[0];
3022
                        else if (connIndex == 2)
3023
                            result = vertices[vertices.Count - 1];
3024

    
3025
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3026
                        {
3027
                            result = new double[] { result[0], result[1] - lineMove };
3028
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3029
                            {
3030
                                result = new double[] { result[0] - lineMove, result[1] };
3031
                            }
3032
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3033
                            {
3034
                                result = new double[] { result[0] + lineMove, result[1] };
3035
                            }
3036
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3037
                            {
3038
                                result = new double[] { result[0] + lineMove, result[1] };
3039
                            }
3040
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3041
                            {
3042
                                result = new double[] { result[0] - lineMove, result[1] };
3043
                            }
3044
                        }
3045
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3046
                        {
3047
                            result = new double[] { result[0] - lineMove, result[1] };
3048
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3049
                            {
3050
                                result = new double[] { result[0], result[1] - lineMove };
3051
                            }
3052
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3053
                            {
3054
                                result = new double[] { result[0], result[1] + lineMove };
3055
                            }
3056
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3057
                            {
3058
                                result = new double[] { result[0], result[1] + lineMove };
3059
                            }
3060
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3061
                            {
3062
                                result = new double[] { result[0], result[1] - lineMove };
3063
                            }
3064
                        }
3065
                            
3066
                    }
3067
                }
3068
                else
3069
                {
3070
                    Log.Write("error in GetSegemtPoint");
3071
                }
3072
            }
3073

    
3074
            return result;
3075
        }
3076

    
3077
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3078
        {
3079
            bool result = false;
3080

    
3081
            foreach (LMRepresentation rep in modelItem.Representations)
3082
            {
3083
                if (result)
3084
                    break;
3085

    
3086
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3087
                {
3088
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3089

    
3090
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3091
                        connector.ConnectItem1SymbolObject != null &&
3092
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3093
                    {
3094
                        result = true;
3095
                        ReleaseCOMObjects(_LMConnector);
3096
                        break;
3097
                    }
3098
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3099
                        connector.ConnectItem2SymbolObject != null &&
3100
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3101
                    {
3102
                        result = true;
3103
                        ReleaseCOMObjects(_LMConnector);
3104
                        break;
3105
                    }
3106
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3107
                        connector.ConnectItem1SymbolObject != null &&
3108
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3109
                    {
3110
                        result = true;
3111
                        ReleaseCOMObjects(_LMConnector);
3112
                        break;
3113
                    }
3114
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3115
                        connector.ConnectItem2SymbolObject != null &&
3116
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3117
                    {
3118
                        result = true;
3119
                        ReleaseCOMObjects(_LMConnector);
3120
                        break;
3121
                    }
3122

    
3123
                    ReleaseCOMObjects(_LMConnector);
3124
                }
3125
            }
3126

    
3127

    
3128
            return result;
3129
        }
3130

    
3131
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3132
        {
3133
            foreach (LMRepresentation rep in modelItem.Representations)
3134
            {
3135
                if (connectedConnector != null)
3136
                    break;
3137

    
3138
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3139
                {
3140
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3141

    
3142
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3143
                        connector.ConnectItem1SymbolObject != null &&
3144
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3145
                    {
3146
                        connectedConnector = _LMConnector;
3147
                        connectorIndex = 1;
3148
                        break;
3149
                    }
3150
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3151
                        connector.ConnectItem2SymbolObject != null &&
3152
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3153
                    {
3154
                        connectedConnector = _LMConnector;
3155
                        connectorIndex = 2;
3156
                        break;
3157
                    }
3158
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3159
                        connector.ConnectItem1SymbolObject != null &&
3160
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3161
                    {
3162
                        connectedConnector = _LMConnector;
3163
                        connectorIndex = 1;
3164
                        break;
3165
                    }
3166
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3167
                        connector.ConnectItem2SymbolObject != null &&
3168
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3169
                    {
3170
                        connectedConnector = _LMConnector;
3171
                        connectorIndex = 2;
3172
                        break;
3173
                    }
3174

    
3175
                    if (connectedConnector == null)
3176
                        ReleaseCOMObjects(_LMConnector);
3177
                }
3178
            }
3179
        }
3180

    
3181
        /// <summary>
3182
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3183
        /// </summary>
3184
        /// <param name="modelItemID1"></param>
3185
        /// <param name="modelItemID2"></param>
3186
        private void JoinRun(string modelId1, string modelId2, ref string survivorId)
3187
        {
3188
            try
3189
            {
3190
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3191
                _LMAItem item1 = modelItem1.AsLMAItem();
3192
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3193
                _LMAItem item2 = modelItem2.AsLMAItem();
3194

    
3195
                // item2가 item1으로 조인
3196
                _placement.PIDJoinRuns(ref item1, ref item2);
3197
                item1.Commit();
3198
                item2.Commit();
3199

    
3200
                string beforeID = string.Empty;
3201
                string afterID = string.Empty;
3202

    
3203
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3204
                {
3205
                    beforeID = modelItem2.Id;
3206
                    afterID = modelItem1.Id;
3207
                    survivorId = afterID;
3208
                    LMAAttribute attribute = modelItem1.Attributes["FlowDirection"];
3209
                    if (attribute != null)
3210
                        attribute.set_Value("End 1 is upstream (Inlet)");
3211
                }
3212
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3213
                {
3214
                    beforeID = modelItem1.Id;
3215
                    afterID = modelItem2.Id;
3216
                    survivorId = afterID;
3217
                    LMAAttribute attribute = modelItem2.Attributes["FlowDirection"];
3218
                    if (attribute != null)
3219
                        attribute.set_Value("End 1 is upstream (Inlet)");
3220
                }
3221
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3222
                    survivorId = null;
3223
                else
3224
                {
3225
                    Log.Write("잘못된 경우");
3226
                    survivorId = null;
3227
                }
3228

    
3229
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3230
                {
3231
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3232
                    foreach (var line in lines)
3233
                        line.SPPID.ModelItemId = afterID;
3234
                }
3235

    
3236
                ReleaseCOMObjects(modelItem1);
3237
                ReleaseCOMObjects(item1);
3238
                ReleaseCOMObjects(modelItem2);
3239
                ReleaseCOMObjects(item2);
3240
            }
3241
            catch (Exception ex)
3242
            {
3243
                Log.Write("Join Error");
3244
                Log.Write(ex.Message);
3245
            }
3246
        }
3247

    
3248
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3249
        {
3250
            List<string> temp = new List<string>();
3251
            List<LMConnector> connectors = new List<LMConnector>();
3252
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3253
            {
3254
                if (connector.get_ItemStatus() != "Active")
3255
                    continue;
3256

    
3257
                LMModelItem modelItem = connector.ModelItemObject;
3258
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3259
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3260
                    temp.Add(modelItem.Id);
3261

    
3262
                if (temp.Contains(modelItem.Id) &&
3263
                    connOtherSymbol != null &&
3264
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3265
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3266
                    temp.Remove(modelItem.Id);
3267

    
3268

    
3269
                if (temp.Contains(modelItem.Id))
3270
                    connectors.Add(connector);
3271
                ReleaseCOMObjects(connOtherSymbol);
3272
                connOtherSymbol = null;
3273
                ReleaseCOMObjects(modelItem);
3274
                modelItem = null;
3275
            }
3276

    
3277
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3278
            {
3279
                if (connector.get_ItemStatus() != "Active")
3280
                    continue;
3281

    
3282
                LMModelItem modelItem = connector.ModelItemObject;
3283
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3284
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3285
                    temp.Add(modelItem.Id);
3286

    
3287
                if (temp.Contains(modelItem.Id) &&
3288
                    connOtherSymbol != null &&
3289
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3290
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3291
                    temp.Remove(modelItem.Id);
3292

    
3293
                if (temp.Contains(modelItem.Id))
3294
                    connectors.Add(connector);
3295
                ReleaseCOMObjects(connOtherSymbol);
3296
                connOtherSymbol = null;
3297
                ReleaseCOMObjects(modelItem);
3298
                modelItem = null;
3299
            }
3300

    
3301

    
3302
            List<string> result = new List<string>();
3303
            string originalName = GetSPPIDFileName(modelId);
3304
            foreach (var connector in connectors)
3305
            {
3306
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3307
                if (originalName == fileName)
3308
                    result.Add(connector.ModelItemID);
3309
                else
3310
                {
3311
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3312
                        result.Add(connector.ModelItemID);
3313
                    else
3314
                    {
3315
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3316
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3317
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3318
                            result.Add(connector.ModelItemID);
3319
                    }
3320
                }
3321
            }
3322

    
3323
            foreach (var connector in connectors)
3324
                ReleaseCOMObjects(connector);
3325
            
3326
            return result;
3327

    
3328

    
3329
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3330
            {
3331
                LMSymbol findResult = null;
3332
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3333
                    findResult = connector.ConnectItem1SymbolObject;
3334
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3335
                    findResult = connector.ConnectItem2SymbolObject;
3336

    
3337
                return findResult;
3338
            }
3339
        }
3340

    
3341
        /// <summary>
3342
        /// PipeRun의 좌표를 가져오는 메서드
3343
        /// </summary>
3344
        /// <param name="modelId"></param>
3345
        /// <returns></returns>
3346
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId)
3347
        {
3348
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3349
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3350

    
3351
            if (modelItem != null)
3352
            {
3353
                foreach (LMRepresentation rep in modelItem.Representations)
3354
                {
3355
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3356
                    {
3357
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3358
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3359
                        dynamic OID = rep.get_GraphicOID().ToString();
3360
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3361
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3362
                        int verticesCount = lineStringGeometry.VertexCount;
3363
                        double[] vertices = null;
3364
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3365
                        for (int i = 0; i < verticesCount; i++)
3366
                        {
3367
                            double x = 0;
3368
                            double y = 0;
3369
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3370
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3371
                        }
3372
                    }
3373
                }
3374

    
3375
                ReleaseCOMObjects(modelItem);
3376
            }
3377

    
3378
            return connectorVertices;
3379
        }
3380

    
3381
        private List<double[]> GetConnectorVertices(LMConnector connector)
3382
        {
3383
            List<double[]> vertices = new List<double[]>();
3384
            if (connector != null)
3385
            {
3386
                dynamic OID = connector.get_GraphicOID().ToString();
3387
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3388
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3389
                int verticesCount = lineStringGeometry.VertexCount;
3390
                double[] value = null;
3391
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3392
                for (int i = 0; i < verticesCount; i++)
3393
                {
3394
                    double x = 0;
3395
                    double y = 0;
3396
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3397
                    vertices.Add(new double[] { x, y });
3398
                }
3399
            }
3400
            return vertices;
3401
        }
3402

    
3403
        /// <summary>
3404
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3405
        /// </summary>
3406
        /// <param name="connectorVertices"></param>
3407
        /// <param name="connX"></param>
3408
        /// <param name="connY"></param>
3409
        /// <returns></returns>
3410
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3411
        {
3412
            double length = double.MaxValue;
3413
            LMConnector targetConnector = null;
3414
            foreach (var item in connectorVertices)
3415
            {
3416
                List<double[]> points = item.Value;
3417
                for (int i = 0; i < points.Count - 1; i++)
3418
                {
3419
                    double[] point1 = points[i];
3420
                    double[] point2 = points[i + 1];
3421
                    double x1 = Math.Min(point1[0], point2[0]);
3422
                    double y1 = Math.Min(point1[1], point2[1]);
3423
                    double x2 = Math.Max(point1[0], point2[0]);
3424
                    double y2 = Math.Max(point1[1], point2[1]);
3425

    
3426
                    if ((x1 <= connX && x2 >= connX) ||
3427
                        (y1 <= connY && y2 >= connY))
3428
                    {
3429
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3430
                        if (length >= distance)
3431
                        {
3432
                            targetConnector = item.Key;
3433
                            length = distance;
3434
                        }
3435

    
3436
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3437
                        if (length >= distance)
3438
                        {
3439
                            targetConnector = item.Key;
3440
                            length = distance;
3441
                        }
3442
                    }
3443
                }
3444
            }
3445

    
3446
            // 못찾았을때.
3447
            length = double.MaxValue;
3448
            if (targetConnector == null)
3449
            {
3450
                foreach (var item in connectorVertices)
3451
                {
3452
                    List<double[]> points = item.Value;
3453

    
3454
                    foreach (double[] point in points)
3455
                    {
3456
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3457
                        if (length >= distance)
3458
                        {
3459
                            targetConnector = item.Key;
3460
                            length = distance;
3461
                        }
3462
                    }
3463
                }
3464
            }
3465

    
3466
            return targetConnector;
3467
        }
3468

    
3469
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3470
        {
3471
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3472
            if (vertices.Count == 0)
3473
                return null;
3474

    
3475
            double length = double.MaxValue;
3476
            LMConnector targetConnector = null;
3477
            double[] resultPoint = null;
3478
            List<double[]> targetVertices = null;
3479

    
3480
            // Vertices 포인트에 제일 가까운곳
3481
            foreach (var item in vertices)
3482
            {
3483
                List<double[]> points = item.Value;
3484
                for (int i = 0; i < points.Count; i++)
3485
                {
3486
                    double[] point = points[i];
3487
                    double tempX = point[0];
3488
                    double tempY = point[1];
3489

    
3490
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3491
                    if (length >= distance)
3492
                    {
3493
                        targetConnector = item.Key;
3494
                        length = distance;
3495
                        resultPoint = point;
3496
                        targetVertices = item.Value;
3497
                    }
3498
                }
3499
            }
3500

    
3501
            // Vertices Cross에 제일 가까운곳
3502
            foreach (var item in vertices)
3503
            {
3504
                List<double[]> points = item.Value;
3505
                for (int i = 0; i < points.Count - 1; i++)
3506
                {
3507
                    double[] point1 = points[i];
3508
                    double[] point2 = points[i + 1];
3509

    
3510
                    double maxLineX = Math.Max(point1[0], point2[0]);
3511
                    double minLineX = Math.Min(point1[0], point2[0]);
3512
                    double maxLineY = Math.Max(point1[1], point2[1]);
3513
                    double minLineY = Math.Min(point1[1], point2[1]);
3514

    
3515
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3516

    
3517
                    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]);
3518
                    if (crossingPoint != null)
3519
                    {
3520
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3521
                        if (length >= distance)
3522
                        {
3523
                            if (slope == SlopeType.Slope &&
3524
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3525
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3526
                            {
3527
                                targetConnector = item.Key;
3528
                                length = distance;
3529
                                resultPoint = crossingPoint;
3530
                                targetVertices = item.Value;
3531
                            }
3532
                            else if (slope == SlopeType.HORIZONTAL &&
3533
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3534
                            {
3535
                                targetConnector = item.Key;
3536
                                length = distance;
3537
                                resultPoint = crossingPoint;
3538
                                targetVertices = item.Value;
3539
                            }
3540
                            else if (slope == SlopeType.VERTICAL &&
3541
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3542
                            {
3543
                                targetConnector = item.Key;
3544
                                length = distance;
3545
                                resultPoint = crossingPoint;
3546
                                targetVertices = item.Value;
3547
                            }
3548
                        }
3549
                    }
3550
                }
3551
            }
3552

    
3553
            foreach (var item in vertices)
3554
                if (item.Key != null && item.Key != targetConnector)
3555
                    ReleaseCOMObjects(item.Key);
3556

    
3557
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3558
            {
3559
                double tempResultX = resultPoint[0];
3560
                double tempResultY = resultPoint[1];
3561
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3562

    
3563
                GridSetting gridSetting = GridSetting.GetInstance();
3564

    
3565
                for (int i = 0; i < targetVertices.Count; i++)
3566
                {
3567
                    double[] point = targetVertices[i];
3568
                    double tempX = targetVertices[i][0];
3569
                    double tempY = targetVertices[i][1];
3570
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3571
                    if (tempX == tempResultX && tempY == tempResultY)
3572
                    {
3573
                        if (i == 0)
3574
                        {
3575
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3576
                            bool containZeroLength = false;
3577
                            if (connSymbol != null)
3578
                            {
3579
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3580
                                {
3581
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3582
                                        containZeroLength = true;
3583
                                }
3584
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3585
                                {
3586
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3587
                                        containZeroLength = true;
3588
                                }
3589
                            }
3590

    
3591
                            if (connSymbol == null ||
3592
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3593
                                containZeroLength)
3594
                            {
3595
                                bool bCalcX = false;
3596
                                bool bCalcY = false;
3597
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3598
                                    bCalcX = true;
3599
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3600
                                    bCalcY = true;
3601
                                else
3602
                                {
3603
                                    bCalcX = true;
3604
                                    bCalcY = true;
3605
                                }
3606

    
3607
                                if (bCalcX)
3608
                                {
3609
                                    double nextX = targetVertices[i + 1][0];
3610
                                    double newX = 0;
3611
                                    if (nextX > tempX)
3612
                                    {
3613
                                        newX = tempX + gridSetting.Length;
3614
                                        if (newX > nextX)
3615
                                            newX = (point[0] + nextX) / 2;
3616
                                    }
3617
                                    else
3618
                                    {
3619
                                        newX = tempX - gridSetting.Length;
3620
                                        if (newX < nextX)
3621
                                            newX = (point[0] + nextX) / 2;
3622
                                    }
3623
                                    resultPoint = new double[] { newX, resultPoint[1] };
3624
                                }
3625

    
3626
                                if (bCalcY)
3627
                                {
3628
                                    double nextY = targetVertices[i + 1][1];
3629
                                    double newY = 0;
3630
                                    if (nextY > tempY)
3631
                                    {
3632
                                        newY = tempY + gridSetting.Length;
3633
                                        if (newY > nextY)
3634
                                            newY = (point[1] + nextY) / 2;
3635
                                    }
3636
                                    else
3637
                                    {
3638
                                        newY = tempY - gridSetting.Length;
3639
                                        if (newY < nextY)
3640
                                            newY = (point[1] + nextY) / 2;
3641
                                    }
3642
                                    resultPoint = new double[] { resultPoint[0], newY };
3643
                                }
3644
                            }
3645
                        }
3646
                        else if (i == targetVertices.Count - 1)
3647
                        {
3648
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
3649
                            bool containZeroLength = false;
3650
                            if (connSymbol != null)
3651
                            {
3652
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3653
                                {
3654
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3655
                                        containZeroLength = true;
3656
                                }
3657
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3658
                                {
3659
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3660
                                        containZeroLength = true;
3661
                                }
3662
                            }
3663

    
3664
                            if (connSymbol == null ||
3665
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3666
                                containZeroLength)
3667
                            {
3668
                                bool bCalcX = false;
3669
                                bool bCalcY = false;
3670
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3671
                                    bCalcX = true;
3672
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3673
                                    bCalcY = true;
3674
                                else
3675
                                {
3676
                                    bCalcX = true;
3677
                                    bCalcY = true;
3678
                                }
3679

    
3680
                                if (bCalcX)
3681
                                {
3682
                                    double nextX = targetVertices[i - 1][0];
3683
                                    double newX = 0;
3684
                                    if (nextX > tempX)
3685
                                    {
3686
                                        newX = tempX + gridSetting.Length;
3687
                                        if (newX > nextX)
3688
                                            newX = (point[0] + nextX) / 2;
3689
                                    }
3690
                                    else
3691
                                    {
3692
                                        newX = tempX - gridSetting.Length;
3693
                                        if (newX < nextX)
3694
                                            newX = (point[0] + nextX) / 2;
3695
                                    }
3696
                                    resultPoint = new double[] { newX, resultPoint[1] };
3697
                                }
3698

    
3699
                                if (bCalcY)
3700
                                {
3701
                                    double nextY = targetVertices[i - 1][1];
3702
                                    double newY = 0;
3703
                                    if (nextY > tempY)
3704
                                    {
3705
                                        newY = tempY + gridSetting.Length;
3706
                                        if (newY > nextY)
3707
                                            newY = (point[1] + nextY) / 2;
3708
                                    }
3709
                                    else
3710
                                    {
3711
                                        newY = tempY - gridSetting.Length;
3712
                                        if (newY < nextY)
3713
                                            newY = (point[1] + nextY) / 2;
3714
                                    }
3715
                                    resultPoint = new double[] { resultPoint[0], newY };
3716
                                }
3717
                            }
3718
                        }
3719
                        break;
3720
                    }
3721
                }
3722
            }
3723

    
3724
            x = resultPoint[0];
3725
            y = resultPoint[1];
3726

    
3727
            return targetConnector;
3728
        }
3729

    
3730
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3731
        {
3732
            LMConnector result = null;
3733
            List<LMConnector> connectors = new List<LMConnector>();
3734
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3735

    
3736
            if (modelItem != null)
3737
            {
3738
                foreach (LMRepresentation rep in modelItem.Representations)
3739
                {
3740
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3741
                        connectors.Add(dataSource.GetConnector(rep.Id));
3742
                }
3743

    
3744
                ReleaseCOMObjects(modelItem);
3745
            }
3746

    
3747
            if (connectors.Count == 1)
3748
                result = connectors[0];
3749
            else
3750
                foreach (var item in connectors)
3751
                    ReleaseCOMObjects(item);
3752

    
3753
            return result;
3754
        }
3755

    
3756
        public List<string> GetRepresentations(string modelItemID)
3757
        {
3758
            List<string> result = new List<string>(); ;
3759
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3760
            if (modelItem != null)
3761
            {
3762
                foreach (LMRepresentation rep in modelItem.Representations)
3763
                {
3764
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3765
                        result.Add(rep.Id);
3766
                }
3767
                ReleaseCOMObjects(modelItem);
3768
            }
3769

    
3770
            return result;
3771
        }
3772

    
3773
        /// <summary>
3774
        /// Line Number Symbol을 실제로 Modeling하는 메서드
3775
        /// </summary>
3776
        /// <param name="lineNumber"></param>
3777
        private void LineNumberModelingOnlyOne(Line line)
3778
        {
3779
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
3780
            if (lineNumber != null)
3781
            {
3782
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3783
                if (connectedLMConnector != null)
3784
                {
3785
                    double x = 0;
3786
                    double y = 0;
3787
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3788

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

    
3792
                    if (_LmLabelPresist != null)
3793
                    {
3794
                        _LmLabelPresist.Commit();
3795
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3796
                        ReleaseCOMObjects(_LmLabelPresist);
3797
                    }
3798
                }
3799
            }
3800
        }
3801

    
3802
        private void LineNumberModeling(LineNumber lineNumber)
3803
        {
3804
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
3805
            if (line != null)
3806
            {
3807
                double x = 0;
3808
                double y = 0;
3809
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
3810

    
3811
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
3812
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
3813
                if (connectedLMConnector != null)
3814
                {
3815
                    Array points = new double[] { 0, x, y };
3816
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
3817

    
3818
                    if (_LmLabelPresist != null)
3819
                    {
3820
                        _LmLabelPresist.Commit();
3821
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3822
                        ReleaseCOMObjects(_LmLabelPresist);
3823
                    }
3824
                }
3825

    
3826
                foreach (var item in connectorVertices)
3827
                    ReleaseCOMObjects(item.Key);
3828
            }
3829
        }
3830
        /// <summary>
3831
        /// Flow Mark Modeling
3832
        /// </summary>
3833
        /// <param name="line"></param>
3834
        private void FlowMarkModeling(Line line)
3835
        {
3836
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
3837
            {
3838
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
3839
                if (connector != null)
3840
                {
3841
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
3842
                    List<double[]> vertices = GetConnectorVertices(connector);
3843
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
3844
                    double[] point = vertices[vertices.Count - 1];
3845
                    Array array = new double[] { 0, point[0], point[1] };
3846
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
3847
                    if (_LMLabelPersist != null)
3848
                    {
3849
                        _LMLabelPersist.Commit();
3850
                        ReleaseCOMObjects(_LMLabelPersist);
3851
                    }
3852
                        
3853
                }
3854
            }
3855
        }
3856

    
3857
        /// <summary>
3858
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
3859
        /// </summary>
3860
        /// <param name="lineNumber"></param>
3861
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
3862
        {
3863
            foreach (LineRun run in lineNumber.RUNS)
3864
            {
3865
                foreach (var item in run.RUNITEMS)
3866
                {
3867
                    if (item.GetType() == typeof(Symbol))
3868
                    {
3869
                        Symbol symbol = item as Symbol;
3870
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3871
                        if (_LMSymbol != null)
3872
                        {
3873
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3874

    
3875
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3876
                            {
3877
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3878
                                {
3879
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3880
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3881
                                    {
3882
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3883
                                        if (_LMAAttribute != null)
3884
                                        {
3885
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3886
                                                _LMAAttribute.set_Value(attribute.VALUE);
3887
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3888
                                                _LMAAttribute.set_Value(attribute.VALUE);
3889
                                        }
3890
                                    }
3891
                                }
3892
                                _LMModelItem.Commit();
3893
                            }
3894
                            if (_LMModelItem != null)
3895
                                ReleaseCOMObjects(_LMModelItem);
3896
                        }
3897
                        if (_LMSymbol != null)
3898
                            ReleaseCOMObjects(_LMSymbol);
3899
                    }
3900
                    else if (item.GetType() == typeof(Line))
3901
                    {
3902
                        Line line = item as Line;
3903
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
3904
                        {
3905
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3906
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
3907
                            {
3908
                                foreach (var attribute in lineNumber.ATTRIBUTES)
3909
                                {
3910
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
3911
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
3912
                                    {
3913
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
3914
                                        if (_LMAAttribute != null)
3915
                                        {
3916
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
3917
                                                _LMAAttribute.set_Value(attribute.VALUE);
3918
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
3919
                                                _LMAAttribute.set_Value(attribute.VALUE);
3920

    
3921
                                        }
3922
                                    }
3923
                                }
3924
                                _LMModelItem.Commit();
3925
                            }
3926
                            if (_LMModelItem != null)
3927
                                ReleaseCOMObjects(_LMModelItem);
3928
                            endLine.Add(line.SPPID.ModelItemId);
3929
                        }
3930
                    }
3931
                }
3932
            }
3933
        }
3934

    
3935
        /// <summary>
3936
        /// Symbol Attribute 입력 메서드
3937
        /// </summary>
3938
        /// <param name="item"></param>
3939
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
3940
        {
3941
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
3942
            string sRep = null;
3943
            if (targetItem.GetType() == typeof(Symbol))
3944
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
3945
            else if (targetItem.GetType() == typeof(Equipment))
3946
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
3947

    
3948
            if (!string.IsNullOrEmpty(sRep))
3949
            {
3950
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
3951
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
3952
                LMAAttributes _Attributes = _LMModelItem.Attributes;
3953
                
3954
                foreach (var item in targetAttributes)
3955
                {
3956
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
3957
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
3958
                    {
3959
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
3960
                        if (_Attribute != null)
3961
                        {
3962
                            //object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
3963
                            //if (associItem != null)
3964
                            //{
3965
                            //    if (associItem.GetType() == typeof(Text))
3966
                            //    {
3967
                            //        Text text = associItem as Text;
3968
                            //        text.SPPID.RepresentationId = "Attribute";
3969
                            //    }
3970
                            //    else if (associItem.GetType() == typeof(Note))
3971
                            //    {
3972
                            //        Note note = associItem as Note;
3973
                            //        note.SPPID.RepresentationId = "Attribute";
3974
                            //    }
3975
                            //}
3976
                            _Attribute.set_Value(item.VALUE);
3977
                            // OPC 일경우 Attribute 저장
3978
                            if (targetItem.GetType() == typeof(Symbol))
3979
                            {
3980
                                Symbol symbol = targetItem as Symbol;
3981
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
3982
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
3983
                            }
3984
                        }
3985
                    }
3986
                }
3987
                _LMModelItem.Commit();
3988

    
3989
                ReleaseCOMObjects(_Attributes);
3990
                ReleaseCOMObjects(_LMModelItem);
3991
                ReleaseCOMObjects(_LMSymbol);
3992
            }
3993
        }
3994

    
3995
        /// <summary>
3996
        /// Input SpecBreak Attribute
3997
        /// </summary>
3998
        /// <param name="specBreak"></param>
3999
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4000
        {
4001
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4002
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4003

    
4004
            if (upStreamObj != null &&
4005
                downStreamObj != null)
4006
            {
4007
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4008

    
4009
                if (targetLMConnector != null)
4010
                {
4011
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4012
                    {
4013
                        string symbolPath = _LMLabelPersist.get_FileName();
4014
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4015
                        if (mapping != null)
4016
                        {
4017
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4018
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4019
                            {
4020
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4021
                                if (values.Length == 2)
4022
                                {
4023
                                    string upStreamValue = values[0];
4024
                                    string downStreamValue = values[1];
4025

    
4026
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4027
                                }
4028
                            }
4029
                        }
4030
                    }
4031

    
4032
                    ReleaseCOMObjects(targetLMConnector);
4033
                }
4034
            }
4035

    
4036

    
4037
            #region 내부에서만 쓰는 메서드
4038
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4039
            {
4040
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4041
                Line upStreamLine = _upStreamObj as Line;
4042
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4043
                Line downStreamLine = _downStreamObj as Line;
4044
                // 둘다 Line일 경우
4045
                if (upStreamLine != null && downStreamLine != null)
4046
                {
4047
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4048
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4049
                }
4050
                // 둘다 Symbol일 경우
4051
                else if (upStreamSymbol != null && downStreamSymbol != null)
4052
                {
4053
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4054
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4055
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4056

    
4057
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4058
                    {
4059
                        if (connector.get_ItemStatus() != "Active")
4060
                            continue;
4061

    
4062
                        if (connector.Id != zeroLenthConnector.Id)
4063
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4064
                    }
4065

    
4066
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4067
                    {
4068
                        if (connector.get_ItemStatus() != "Active")
4069
                            continue;
4070

    
4071
                        if (connector.Id != zeroLenthConnector.Id)
4072
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4073
                    }
4074

    
4075
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4076
                    {
4077
                        if (connector.get_ItemStatus() != "Active")
4078
                            continue;
4079

    
4080
                        if (connector.Id != zeroLenthConnector.Id)
4081
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4082
                    }
4083

    
4084
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4085
                    {
4086
                        if (connector.get_ItemStatus() != "Active")
4087
                            continue;
4088

    
4089
                        if (connector.Id != zeroLenthConnector.Id)
4090
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4091
                    }
4092

    
4093
                    ReleaseCOMObjects(zeroLenthConnector);
4094
                    ReleaseCOMObjects(upStreamLMSymbol);
4095
                    ReleaseCOMObjects(downStreamLMSymbol);
4096
                }
4097
                else if (upStreamSymbol != null && downStreamLine != null)
4098
                {
4099
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4100
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4101
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4102

    
4103
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4104
                    {
4105
                        if (connector.get_ItemStatus() != "Active")
4106
                            continue;
4107

    
4108
                        if (connector.Id == zeroLenthConnector.Id)
4109
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4110
                    }
4111

    
4112
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4113
                    {
4114
                        if (connector.get_ItemStatus() != "Active")
4115
                            continue;
4116

    
4117
                        if (connector.Id == zeroLenthConnector.Id)
4118
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4119
                    }
4120

    
4121
                    ReleaseCOMObjects(zeroLenthConnector);
4122
                    ReleaseCOMObjects(upStreamLMSymbol);
4123
                }
4124
                else if (upStreamLine != null && downStreamSymbol != null)
4125
                {
4126
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4127
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4128
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4129

    
4130
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4131
                    {
4132
                        if (connector.get_ItemStatus() != "Active")
4133
                            continue;
4134

    
4135
                        if (connector.Id == zeroLenthConnector.Id)
4136
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4137
                    }
4138

    
4139
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4140
                    {
4141
                        if (connector.get_ItemStatus() != "Active")
4142
                            continue;
4143

    
4144
                        if (connector.Id == zeroLenthConnector.Id)
4145
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4146
                    }
4147

    
4148
                    ReleaseCOMObjects(zeroLenthConnector);
4149
                    ReleaseCOMObjects(downStreamLMSymbol);
4150
                }
4151
            }
4152

    
4153
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4154
            {
4155
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4156
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4157
                {
4158
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4159
                    if (_LMAAttribute != null)
4160
                    {
4161
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4162
                            _LMAAttribute.set_Value(value);
4163
                        else if (_LMAAttribute.get_Value() != value)
4164
                            _LMAAttribute.set_Value(value);
4165
                    }
4166

    
4167
                    _LMModelItem.Commit();
4168
                }
4169
                if (_LMModelItem != null)
4170
                    ReleaseCOMObjects(_LMModelItem);
4171
            }
4172

    
4173
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4174
            {
4175
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4176
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4177
                {
4178
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4179
                    if (_LMAAttribute != null)
4180
                    {
4181
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4182
                            _LMAAttribute.set_Value(value);
4183
                        else if (_LMAAttribute.get_Value() != value)
4184
                            _LMAAttribute.set_Value(value);
4185
                    }
4186

    
4187
                    _LMModelItem.Commit();
4188
                }
4189
                if (_LMModelItem != null)
4190
                    ReleaseCOMObjects(_LMModelItem);
4191
            }
4192
            #endregion
4193
        }
4194

    
4195
        /// <summary>
4196
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
4197
        /// </summary>
4198
        /// <param name="text"></param>
4199
        private void TextModeling(Text text, List<Text> correctList)
4200
        {
4201
            LMSymbol _LMSymbol = null;
4202
            LMConnector connectedLMConnector = null;
4203
            //if (text.ASSOCIATION && !string.IsNullOrEmpty(text.OWNER) && text.OWNER != "None")
4204
            if (text.ASSOCIATION)
4205
            {
4206
                object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4207
                if (owner != null && owner.GetType() == typeof(Symbol))
4208
                {
4209
                    Symbol symbol = owner as Symbol;
4210
                    _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4211
                    if (_LMSymbol != null)
4212
                    {
4213
                        BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4214
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4215
                        {
4216
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4217

    
4218
                            if (mapping != null)
4219
                            {
4220
                                double x = 0;
4221
                                double y = 0;
4222

    
4223
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4224
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
4225
                                Array array = new double[] { 0, x, y };
4226
                                text.SPPID.SPPID_X = x;
4227
                                text.SPPID.SPPID_Y = y;
4228
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4229
                                if (_LMLabelPersist != null)
4230
                                {
4231
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4232
                                    _LMLabelPersist.Commit();
4233
                                    ReleaseCOMObjects(_LMLabelPersist);
4234
                                }
4235
                            }
4236
                        }
4237
                    }
4238
                }
4239
                else if (owner != null && owner.GetType() == typeof(Line))
4240
                {
4241
                    Line line = owner as Line;
4242
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4243
                    connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
4244

    
4245
                    if (connectedLMConnector != null)
4246
                    {
4247
                        BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4248
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4249
                        {
4250
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4251

    
4252
                            if (mapping != null)
4253
                            {
4254
                                double x = 0;
4255
                                double y = 0;
4256
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
4257
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
4258
                                Array array = new double[] { 0, x, y };
4259

    
4260
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4261
                                if (_LMLabelPersist != null)
4262
                                {
4263
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4264
                                    _LMLabelPersist.Commit();
4265
                                    ReleaseCOMObjects(_LMLabelPersist);
4266
                                }
4267
                            }
4268
                        }
4269
                    }
4270
                }
4271
            }
4272
            else
4273
            {
4274
                LMItemNote _LMItemNote = null;
4275
                LMAAttribute _LMAAttribute = null;
4276

    
4277
                double x = 0;
4278
                double y = 0;
4279
                double angle = text.ANGLE;
4280
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
4281

    
4282
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
4283
                text.SPPID.SPPID_X = x;
4284
                text.SPPID.SPPID_Y = y;
4285

    
4286
                _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
4287
                if (_LMSymbol != null)
4288
                {
4289
                    _LMSymbol.Commit();
4290
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4291
                    if (_LMItemNote != null)
4292
                    {
4293
                        _LMItemNote.Commit();
4294
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4295
                        if (_LMAAttribute != null)
4296
                        {
4297
                            _LMAAttribute.set_Value(text.VALUE);
4298
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4299
                            _LMItemNote.Commit();
4300

    
4301

    
4302
                            double[] range = null;
4303
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4304
                            {
4305
                                double[] temp = null;
4306
                                GetSPPIDSymbolRange(labelPersist, ref temp);
4307
                                if (temp != null)
4308
                                {
4309
                                    if (range == null)
4310
                                        range = temp;
4311
                                    else
4312
                                    {
4313
                                        range = new double[] {
4314
                                            Math.Min(range[0], temp[0]),
4315
                                            Math.Min(range[1], temp[1]),
4316
                                            Math.Max(range[2], temp[2]),
4317
                                            Math.Max(range[3], temp[3])
4318
                                        };
4319
                                    }
4320
                                }
4321
                            }
4322
                            if (range != null)
4323
                                correctList.Add(text);
4324
                            text.SPPID.Range = range;
4325

    
4326

    
4327
                            if (_LMAAttribute != null)
4328
                                ReleaseCOMObjects(_LMAAttribute);
4329
                            if (_LMItemNote != null)
4330
                                ReleaseCOMObjects(_LMItemNote);
4331
                        }
4332
                    }
4333
                }
4334
            }
4335
            if (_LMSymbol != null)
4336
                ReleaseCOMObjects(_LMSymbol);
4337
        }
4338

    
4339
        private void TextCorrectModeling(Text text, List<Text> endList)
4340
        {
4341
            bool needRemodeling = false;
4342
            bool loop = true;
4343
            GridSetting gridSetting = GridSetting.GetInstance();
4344
            while (loop)
4345
            {
4346
                loop = false;
4347
                foreach (var overlapText in endList)
4348
                {
4349
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
4350
                    {
4351
                        double tempX = 0;
4352
                        double tempY = 0;
4353
                        bool overlapX = false;
4354
                        bool overlapY = false;
4355
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4356
                        double angle = SPPIDUtil.CalcAngle(text.LOCATION_X, text.LOCATION_Y, overlapText.LOCATION_X, overlapText.LOCATION_Y);
4357
                        if (overlapY && angle >= 45)
4358
                        {
4359
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4360
                            double move = gridSetting.Length * count;
4361
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
4362
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
4363
                            needRemodeling = true;
4364
                            loop = true;
4365
                        }
4366
                        if (overlapX && angle <= 45)
4367
                        {
4368
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4369
                            double move = gridSetting.Length * count;
4370
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
4371
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
4372
                            needRemodeling = true;
4373
                            loop = true;
4374
                        }
4375
                    }
4376
                }
4377
            }
4378
            
4379

    
4380
            if (needRemodeling)
4381
            {
4382
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
4383
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4384
                text.SPPID.RepresentationId = null;
4385

    
4386
                LMItemNote _LMItemNote = null;
4387
                LMAAttribute _LMAAttribute = null;
4388
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
4389
                if (_LMSymbol != null)
4390
                {
4391
                    _LMSymbol.Commit();
4392
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4393
                    if (_LMItemNote != null)
4394
                    {
4395
                        _LMItemNote.Commit();
4396
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4397
                        if (_LMAAttribute != null)
4398
                        {
4399
                            _LMAAttribute.set_Value(text.VALUE);
4400
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4401
                            _LMItemNote.Commit();
4402

    
4403
                            ReleaseCOMObjects(_LMAAttribute);
4404
                            ReleaseCOMObjects(_LMItemNote);
4405
                        }
4406
                    }
4407
                }
4408

    
4409
                ReleaseCOMObjects(symbol);
4410
                symbol = null;
4411
                ReleaseCOMObjects(_LMItemNote);
4412
                _LMItemNote = null;
4413
                ReleaseCOMObjects(_LMAAttribute);
4414
                _LMAAttribute = null;
4415
                ReleaseCOMObjects(_LMSymbol);
4416
                _LMSymbol = null;
4417
            }
4418

    
4419
            endList.Add(text);
4420
        }
4421

    
4422
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
4423
        {
4424
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
4425
            {
4426
                List<Text> texts = new List<Text>();
4427
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
4428
                LMRepresentation representation = targetLabel.RepresentationObject;
4429
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
4430
                if (targetLabel.RepresentationObject != null && symbol != null)
4431
                {
4432
                    double[] symbolRange = null;
4433
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
4434
                    if (symbolRange != null)
4435
                    {
4436
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
4437
                        {
4438
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
4439
                            if (findText != null)
4440
                            {
4441
                                double[] range = null;
4442
                                GetSPPIDSymbolRange(labelPersist, ref range);
4443
                                findText.SPPID.Range = range;
4444
                                texts.Add(findText);
4445
                            }
4446

    
4447
                            ReleaseCOMObjects(labelPersist);
4448
                        }
4449

    
4450
                        if (texts.Count > 0)
4451
                        {
4452
                            #region Sort Text By Y
4453
                            texts.Sort(SortTextByY);
4454
                            int SortTextByY(Text a, Text b)
4455
                            {
4456
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
4457
                            }
4458
                            #endregion
4459

    
4460
                            #region 첫번째 Text로 기준 맞춤
4461
                            for (int i = 0; i < texts.Count; i++)
4462
                            {
4463
                                if (i != 0)
4464
                                {
4465
                                    Text currentText = texts[i];
4466
                                    Text prevText = texts[i - 1];
4467
                                    double minY = prevText.SPPID.Range[1];
4468
                                    double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
4469
                                    double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
4470
                                    double _gapX = centerX - centerPrevX;
4471
                                    double _gapY = currentText.SPPID.Range[3] - minY;
4472
                                    MoveText(currentText, _gapX, _gapY);
4473
                                }
4474
                            }
4475
                            List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
4476
                            List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
4477
                            List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
4478
                            List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
4479
                            rangeMinX.Sort();
4480
                            rangeMinY.Sort();
4481
                            rangeMaxX.Sort();
4482
                            rangeMaxY.Sort();
4483
                            double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
4484
                            double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
4485
                            #endregion
4486

    
4487
                            Text correctBySymbol = texts[0];
4488
                            double textCenterX = (text.X1 + text.X2) / 2;
4489
                            double textCenterY = (text.Y1 + text.Y2) / 2;
4490
                            double originX = 0;
4491
                            double originY = 0;
4492
                            SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
4493
                            double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
4494
                            double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
4495
                            double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
4496

    
4497
                            double gapX = 0;
4498
                            double gapY = 0;
4499
                            if (angle < 45)
4500
                            {
4501
                                // Text 오른쪽
4502
                                if (textCenterX > originX)
4503
                                {
4504
                                    gapX = rangeMinX[0] - symbolRange[2];
4505
                                    gapY = allTextCenterY - symbolCenterY;
4506
                                }
4507
                                // Text 왼쪽
4508
                                else
4509
                                {
4510
                                    gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
4511
                                    gapY = allTextCenterY - symbolCenterY;
4512
                                }
4513
                            }
4514
                            else
4515
                            {
4516
                                // Text 아래쪽
4517
                                if (textCenterY > originY)
4518
                                {
4519
                                    gapX = allTextCenterX - symbolCenterX;
4520
                                    gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
4521
                                }
4522
                                // Text 위쪽
4523
                                else
4524
                                {
4525
                                    gapX = allTextCenterX - symbolCenterX;
4526
                                    gapY = rangeMinY[0] - symbolRange[3];
4527
                                }
4528
                            }
4529

    
4530
                            foreach (var item in texts)
4531
                            {
4532
                                MoveText(item, gapX, gapY);
4533
                                RemodelingAssociationText(item);
4534
                            }
4535
                        }
4536
                    }
4537
                }
4538

    
4539
                void MoveText(Text moveText, double x, double y)
4540
                {
4541
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
4542
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
4543
                    moveText.SPPID.Range = new double[] {
4544
                        moveText.SPPID.Range[0] - x,
4545
                        moveText.SPPID.Range[1]- y,
4546
                        moveText.SPPID.Range[2]- x,
4547
                        moveText.SPPID.Range[3]- y
4548
                    };
4549
                }
4550

    
4551
                endTexts.AddRange(texts);
4552

    
4553
                ReleaseCOMObjects(targetLabel);
4554
                targetLabel = null;
4555
                ReleaseCOMObjects(representation);
4556
                representation = null;
4557
            }
4558
        }
4559

    
4560
        private void RemodelingAssociationText(Text text)
4561
        {
4562
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
4563
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4564
            removeLabel.Commit();
4565
            ReleaseCOMObjects(removeLabel);
4566
            removeLabel = null;
4567

    
4568
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4569
            if (owner != null && owner.GetType() == typeof(Symbol))
4570
            {
4571
                Symbol symbol = owner as Symbol;
4572
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4573
                if (_LMSymbol != null)
4574
                {
4575
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4576
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4577
                    {
4578
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4579

    
4580
                        if (mapping != null)
4581
                        {
4582
                            double x = 0;
4583
                            double y = 0;
4584

    
4585
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
4586
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
4587
                            if (_LMLabelPersist != null)
4588
                            {
4589
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
4590
                                _LMLabelPersist.Commit();
4591
                            }
4592
                            ReleaseCOMObjects(_LMLabelPersist);
4593
                            _LMLabelPersist = null;
4594
                        }
4595
                    }
4596
                }
4597
                ReleaseCOMObjects(_LMSymbol);
4598
                _LMSymbol = null;
4599
            }
4600
        }
4601

    
4602
        /// <summary>
4603
        /// Note Modeling
4604
        /// </summary>
4605
        /// <param name="note"></param>
4606
        private void NoteModeling(Note note, List<Note> correctList)
4607
        {
4608
            LMSymbol _LMSymbol = null;
4609
            LMItemNote _LMItemNote = null;
4610
            LMAAttribute _LMAAttribute = null;
4611

    
4612
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
4613
            {
4614
                double x = 0;
4615
                double y = 0;
4616

    
4617
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
4618
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
4619
                note.SPPID.SPPID_X = x;
4620
                note.SPPID.SPPID_Y = y;
4621

    
4622
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
4623
                if (_LMSymbol != null)
4624
                {
4625
                    _LMSymbol.Commit();
4626
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4627
                    if (_LMItemNote != null)
4628
                    {
4629
                        _LMItemNote.Commit();
4630
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4631
                        if (_LMAAttribute != null)
4632
                        {
4633
                            _LMAAttribute.set_Value(note.VALUE);
4634
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4635

    
4636
                            double[] range = null;
4637
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4638
                            {
4639
                                double[] temp = null;
4640
                                GetSPPIDSymbolRange(labelPersist, ref temp);
4641
                                if (temp != null)
4642
                                {
4643
                                    if (range == null)
4644
                                        range = temp;
4645
                                    else
4646
                                    {
4647
                                        range = new double[] {
4648
                                            Math.Min(range[0], temp[0]),
4649
                                            Math.Min(range[1], temp[1]),
4650
                                            Math.Max(range[2], temp[2]),
4651
                                            Math.Max(range[3], temp[3])
4652
                                        };
4653
                                    }
4654
                                }
4655
                            }
4656
                            if (range != null)
4657
                                correctList.Add(note);
4658
                            note.SPPID.Range = range;
4659

    
4660

    
4661
                            _LMItemNote.Commit();
4662
                        }
4663
                    }
4664
                }
4665
            }
4666

    
4667
            if (_LMAAttribute != null)
4668
                ReleaseCOMObjects(_LMAAttribute);
4669
            if (_LMItemNote != null)
4670
                ReleaseCOMObjects(_LMItemNote);
4671
            if (_LMSymbol != null)
4672
                ReleaseCOMObjects(_LMSymbol);
4673
        }
4674

    
4675
        private void NoteCorrectModeling(Note note, List<Note> endList)
4676
        {
4677
            bool needRemodeling = false;
4678
            bool loop = true;
4679
            GridSetting gridSetting = GridSetting.GetInstance();
4680
            while (loop)
4681
            {
4682
                loop = false;
4683
                foreach (var overlap in endList)
4684
                {
4685
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
4686
                    {
4687
                        double tempX = 0;
4688
                        double tempY = 0;
4689
                        bool overlapX = false;
4690
                        bool overlapY = false;
4691
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
4692
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
4693
                        if (overlapY && angle >= 45)
4694
                        {
4695
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
4696
                            double move = gridSetting.Length * count;
4697
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
4698
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
4699
                            needRemodeling = true;
4700
                            loop = true;
4701
                        }
4702
                        if (overlapX && angle <= 45)
4703
                        {
4704
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
4705
                            double move = gridSetting.Length * count;
4706
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
4707
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
4708
                            needRemodeling = true;
4709
                            loop = true;
4710
                        }
4711
                    }
4712
                }
4713
            }
4714

    
4715

    
4716
            if (needRemodeling)
4717
            {
4718
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
4719
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
4720
                note.SPPID.RepresentationId = null;
4721

    
4722
                LMItemNote _LMItemNote = null;
4723
                LMAAttribute _LMAAttribute = null;
4724
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
4725
                if (_LMSymbol != null)
4726
                {
4727
                    _LMSymbol.Commit();
4728
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4729
                    if (_LMItemNote != null)
4730
                    {
4731
                        _LMItemNote.Commit();
4732
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4733
                        if (_LMAAttribute != null)
4734
                        {
4735
                            _LMAAttribute.set_Value(note.VALUE);
4736
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4737
                            _LMItemNote.Commit();
4738

    
4739
                            ReleaseCOMObjects(_LMAAttribute);
4740
                            ReleaseCOMObjects(_LMItemNote);
4741
                        }
4742
                    }
4743
                }
4744

    
4745
                ReleaseCOMObjects(symbol);
4746
                symbol = null;
4747
                ReleaseCOMObjects(_LMItemNote);
4748
                _LMItemNote = null;
4749
                ReleaseCOMObjects(_LMAAttribute);
4750
                _LMAAttribute = null;
4751
                ReleaseCOMObjects(_LMSymbol);
4752
                _LMSymbol = null;
4753
            }
4754

    
4755
            endList.Add(note);
4756
        }
4757

    
4758
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
4759
        {
4760
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
4761
            if (modelItem != null)
4762
            {
4763
                foreach (LMRepresentation rep in modelItem.Representations)
4764
                {
4765
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4766
                    {
4767
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4768
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4769
                        {
4770
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
4771
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
4772
                            if (modelItemIds.Count == 1)
4773
                            {
4774
                                string joinModelItemId = modelItemIds[0];
4775
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
4776
                                if (survivorId != null)
4777
                                    break;
4778
                            }
4779
                        }
4780
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4781
                        {
4782
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
4783
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
4784
                            if (modelItemIds.Count == 1)
4785
                            {
4786
                                string joinModelItemId = modelItemIds[0];
4787
                                JoinRun(joinModelItemId, modelItemId, ref survivorId);
4788
                                if (survivorId != null)
4789
                                    break;
4790
                            }
4791
                        }
4792
                    }
4793
                }
4794
            }
4795
        }
4796

    
4797
        /// <summary>
4798
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
4799
        /// </summary>
4800
        /// <param name="x"></param>
4801
        /// <param name="y"></param>
4802
        /// <param name="originX"></param>
4803
        /// <param name="originY"></param>
4804
        /// <param name="SPPIDLabelLocation"></param>
4805
        /// <param name="location"></param>
4806
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
4807
        {
4808
            if (location == Location.None)
4809
            {
4810
                x = originX;
4811
                y = originY;
4812
            }
4813
            else
4814
            {
4815
                if (location.HasFlag(Location.Center))
4816
                {
4817
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
4818
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
4819
                }
4820

    
4821
                if (location.HasFlag(Location.Left))
4822
                    x = SPPIDLabelLocation.X1;
4823
                else if (location.HasFlag(Location.Right))
4824
                    x = SPPIDLabelLocation.X2;
4825

    
4826
                if (location.HasFlag(Location.Down))
4827
                    y = SPPIDLabelLocation.Y1;
4828
                else if (location.HasFlag(Location.Up))
4829
                    y = SPPIDLabelLocation.Y2;
4830
            }
4831
        }
4832

    
4833
        /// <summary>
4834
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
4835
        /// 1. Angle Valve
4836
        /// 2. 3개로 이루어진 Symbol Group
4837
        /// </summary>
4838
        /// <returns></returns>
4839
        private List<Symbol> GetPrioritySymbol()
4840
        {
4841
            DataTable symbolTable = document.SymbolTable;
4842
            // List에 순서대로 쌓는다.
4843
            List<Symbol> symbols = new List<Symbol>();
4844

    
4845
            // Angle Valve 부터
4846
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
4847
            {
4848
                if (!symbols.Contains(symbol))
4849
                {
4850
                    double originX = 0;
4851
                    double originY = 0;
4852

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

    
4857
                    SlopeType slopeType1 = SlopeType.None;
4858
                    SlopeType slopeType2 = SlopeType.None;
4859
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
4860
                    {
4861
                        double connectorX = 0;
4862
                        double connectorY = 0;
4863
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
4864
                        if (slopeType1 == SlopeType.None)
4865
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
4866
                        else
4867
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
4868
                    }
4869

    
4870
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
4871
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
4872
                        symbols.Add(symbol);
4873
                }
4874
            }
4875

    
4876
            List<Symbol> tempSymbols = new List<Symbol>();
4877
            // Conn 갯수 기준
4878
            foreach (var item in document.SYMBOLS)
4879
            {
4880
                if (!symbols.Contains(item))
4881
                    tempSymbols.Add(item);
4882
            }
4883
            tempSymbols.Sort(SortSymbolPriority);
4884
            symbols.AddRange(tempSymbols);
4885

    
4886
            return symbols;
4887
        }
4888

    
4889
        private void SetPriorityLine(List<Line> lines)
4890
        {
4891
            lines.Sort(SortLinePriority);
4892

    
4893
            int SortLinePriority(Line a, Line b)
4894
            {
4895
                // Branch 없는것부터
4896
                int branchRetval = CompareBranchLine(a, b);
4897
                if (branchRetval != 0)
4898
                {
4899
                    return branchRetval;
4900
                }
4901
                else
4902
                {
4903
                    // Symbol 연결 갯수
4904
                    int connSymbolRetval = CompareConnSymbol(a, b);
4905
                    if (connSymbolRetval != 0)
4906
                    {
4907
                        return connSymbolRetval;
4908
                    }
4909
                    else
4910
                    {
4911
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
4912
                        int connItemRetval = CompareConnItem(a, b);
4913
                        if (connItemRetval != 0)
4914
                        {
4915
                            return connItemRetval;
4916
                        }
4917
                        else
4918
                        {
4919
                            // ConnectedItem이 없는것
4920
                            int noneConnRetval = CompareNoneConn(a, b);
4921
                            if (noneConnRetval != 0)
4922
                            {
4923
                                return noneConnRetval;
4924
                            }
4925
                            else
4926
                            {
4927

    
4928
                            }
4929
                        }
4930
                    }
4931
                }
4932

    
4933
                return 0;
4934
            }
4935

    
4936
            int CompareNotSegmentLine(Line a, Line b)
4937
            {
4938
                List<Connector> connectorsA = a.CONNECTORS
4939
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4940
                    .ToList();
4941

    
4942
                List<Connector> connectorsB = b.CONNECTORS
4943
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4944
                    .ToList();
4945

    
4946
                // 오름차순
4947
                return connectorsB.Count.CompareTo(connectorsA.Count);
4948
            }
4949

    
4950
            int CompareConnSymbol(Line a, Line b)
4951
            {
4952
                List<Connector> connectorsA = a.CONNECTORS
4953
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4954
                    .ToList();
4955

    
4956
                List<Connector> connectorsB = b.CONNECTORS
4957
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4958
                    .ToList();
4959

    
4960
                // 오름차순
4961
                return connectorsB.Count.CompareTo(connectorsA.Count);
4962
            }
4963

    
4964
            int CompareConnItem(Line a, Line b)
4965
            {
4966
                List<Connector> connectorsA = a.CONNECTORS
4967
                    .Where(conn => conn.ConnectedObject != null && 
4968
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
4969
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
4970
                    .ToList();
4971

    
4972
                List<Connector> connectorsB = b.CONNECTORS
4973
                    .Where(conn => conn.ConnectedObject != null &&
4974
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
4975
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
4976
                    .ToList();
4977

    
4978
                // 오름차순
4979
                return connectorsB.Count.CompareTo(connectorsA.Count);
4980
            }
4981

    
4982
            int CompareBranchLine(Line a, Line b)
4983
            {
4984
                List<Connector> connectorsA = a.CONNECTORS
4985
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
4986
                    .ToList();
4987
                List<Connector> connectorsB = b.CONNECTORS
4988
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
4989
                    .ToList();
4990

    
4991
                // 내림차순
4992
                return connectorsA.Count.CompareTo(connectorsB.Count);
4993
            }
4994

    
4995
            int CompareNoneConn(Line a, Line b)
4996
            {
4997
                List<Connector> connectorsA = a.CONNECTORS
4998
                    .Where(conn => conn.ConnectedObject == null)
4999
                    .ToList();
5000

    
5001
                List<Connector> connectorsB = b.CONNECTORS
5002
                    .Where(conn => conn.ConnectedObject == null)
5003
                    .ToList();
5004

    
5005
                // 오름차순
5006
                return connectorsB.Count.CompareTo(connectorsA.Count);
5007
            }
5008
        }
5009

    
5010
        private void SortText(List<Text> texts)
5011
        {
5012
            texts.Sort(Sort);
5013

    
5014
            int Sort(Text a, Text b)
5015
            {
5016
                int yRetval = CompareY(a, b);
5017
                if (yRetval != 0)
5018
                {
5019
                    return yRetval;
5020
                }
5021
                else
5022
                {
5023
                    return CompareX(a, b);
5024
                }
5025
            }
5026

    
5027
            int CompareY(Text a, Text b)
5028
            {
5029
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5030
            }
5031

    
5032
            int CompareX(Text a, Text b)
5033
            {
5034
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5035
            }
5036
        }
5037
        private void SortNote(List<Note> notes)
5038
        {
5039
            notes.Sort(Sort);
5040

    
5041
            int Sort(Note a, Note b)
5042
            {
5043
                int yRetval = CompareY(a, b);
5044
                if (yRetval != 0)
5045
                {
5046
                    return yRetval;
5047
                }
5048
                else
5049
                {
5050
                    return CompareX(a, b);
5051
                }
5052
            }
5053

    
5054
            int CompareY(Note a, Note b)
5055
            {
5056
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5057
            }
5058

    
5059
            int CompareX(Note a, Note b)
5060
            {
5061
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5062
            }
5063
        }
5064

    
5065
        private void SortBranchLines()
5066
        {
5067
            BranchLines.Sort(SortBranchLine);
5068
            int SortBranchLine(Line a, Line b)
5069
            {
5070
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5071
                 x.ConnectedObject.GetType() == typeof(Line) &&
5072
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
5073
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5074

    
5075
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5076
                 x.ConnectedObject.GetType() == typeof(Line) &&
5077
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
5078
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5079

    
5080
                // 내림차순
5081
                return countA.CompareTo(countB);
5082
            }
5083
        }
5084

    
5085
        private static int SortSymbolPriority(Symbol a, Symbol b)
5086
        {
5087
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5088
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5089
            int retval = countB.CompareTo(countA);
5090
            if (retval != 0)
5091
                return retval;
5092
            else
5093
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
5094
        }
5095

    
5096
        private string GetSPPIDFileName(LMModelItem modelItem)
5097
        {
5098
            string symbolPath = null;
5099
            foreach (LMRepresentation rep in modelItem.Representations)
5100
            {
5101
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5102
                {
5103
                    symbolPath = rep.get_FileName();
5104
                    break;
5105
                }
5106
            }
5107
            return symbolPath;
5108
        }
5109

    
5110
        private string GetSPPIDFileName(string modelItemId)
5111
        {
5112
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5113
            string symbolPath = null;
5114
            foreach (LMRepresentation rep in modelItem.Representations)
5115
            {
5116
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5117
                {
5118
                    symbolPath = rep.get_FileName();
5119
                    break;
5120
                }
5121
            }
5122
            ReleaseCOMObjects(modelItem);
5123
            return symbolPath;
5124
        }
5125

    
5126
        /// <summary>
5127
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
5128
        /// </summary>
5129
        /// <param name="graphicOID"></param>
5130
        /// <param name="milliseconds"></param>
5131
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
5132
        {
5133
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
5134
            {
5135
                double minX = 0;
5136
                double minY = 0;
5137
                double maxX = 0;
5138
                double maxY = 0;
5139
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
5140
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
5141

    
5142
                Thread.Sleep(milliseconds);
5143
            }
5144
        }
5145

    
5146
        /// <summary>
5147
        /// ComObject를 Release
5148
        /// </summary>
5149
        /// <param name="objVars"></param>
5150
        public void ReleaseCOMObjects(params object[] objVars)
5151
        {
5152
            if (objVars != null)
5153
            {
5154
                int intNewRefCount = 0;
5155
                foreach (object obj in objVars)
5156
                {
5157
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
5158
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
5159
                }
5160
            }
5161
        }
5162

    
5163
        /// IDisposable 구현
5164
        ~AutoModeling()
5165
        {
5166
            this.Dispose(false);
5167
        }
5168

    
5169
        private bool disposed;
5170
        public void Dispose()
5171
        {
5172
            this.Dispose(true);
5173
            GC.SuppressFinalize(this);
5174
        }
5175

    
5176
        protected virtual void Dispose(bool disposing)
5177
        {
5178
            if (this.disposed) return;
5179
            if (disposing)
5180
            {
5181
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
5182
            }
5183
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
5184
            this.disposed = true;
5185
        }
5186
    }
5187
}
클립보드 이미지 추가 (최대 크기: 500 MB)