프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 0fca6839

이력 | 보기 | 이력해설 | 다운로드 (191 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Data;
7
using Llama;
8
using Plaice;
9
using Ingr.RAD2D.Interop.RAD2D;
10
using Ingr.RAD2D.Internal;
11
using Ingr.RAD2D.Helper;
12
using Converter.BaseModel;
13
using Converter.SPPID.Model;
14
using Converter.SPPID.Properties;
15
using Converter.SPPID.Util;
16
using Converter.SPPID.DB;
17
using Ingr.RAD2D.MacroControls.CmdCtrl;
18
using Ingr.RAD2D;
19
using System.Windows;
20
using System.Threading;
21
using System.Drawing;
22
using Microsoft.VisualBasic;
23
using Newtonsoft.Json;
24
using DevExpress.XtraSplashScreen;
25
namespace Converter.SPPID
26
{
27
    public class AutoModeling : IDisposable
28
    {
29
        Placement _placement;
30
        LMADataSource dataSource;
31
        string drawingID;
32
        dynamic newDrawing;
33
        dynamic application;
34
        bool closeDocument;
35
        Ingr.RAD2D.Application radApp;
36
        SPPID_Document document;
37
        ETCSetting _ETCSetting;
38

    
39
        public string DocumentLabelText { get; set; }
40

    
41
        List<Line> BranchLines = new List<Line>();
42
        List<string> ZeroLengthSymbolToSymbolModelItemID = new List<string>();
43
        List<string> ZeroLengthModelItemID = new List<string>();
44
        List<string> ZeroLengthModelItemIDReverse = new List<string>();
45
        List<Symbol> prioritySymbols;
46

    
47
        public AutoModeling(SPPID_Document document, bool closeDocument)
48
        {
49
            application = Interaction.GetObject("", "PIDAutomation.Application");
50
            WrapperApplication wApp = new WrapperApplication(application.Application);
51
            radApp = wApp.RADApplication;
52

    
53
            this.closeDocument = closeDocument;
54
            this.document = document;
55
            this._ETCSetting = ETCSetting.GetInstance();
56
        }
57

    
58
        private void SetSystemEditingCommand(bool value)
59
        {
60
            foreach (var item in radApp.Commands)
61
            {
62
                if (item.Argument == "SystemEditingCmd.SystemEditing")
63
                {
64
                    if (item.Checked != value)
65
                    {
66
                        radApp.RunMacro("systemeditingcmd.dll");
67
                        break;
68
                    }
69

    
70
                }
71
            }
72
        }
73

    
74
        /// <summary>
75
        /// 도면 단위당 실행되는 메서드
76
        /// </summary>
77
        public void Run()
78
        {
79
            string drawingNumber = document.DrawingNumber;
80
            string drawingName = document.DrawingName;
81
            try
82
            {
83
                _placement = new Placement();
84
                dataSource = _placement.PIDDataSource;
85

    
86
                if (CreateDocument(ref drawingNumber, ref drawingName) && DocumentCoordinateCorrection())
87
                {
88
                    Log.Write("Start Modeling");
89
                    SplashScreenManager.ShowForm(typeof(SPPIDSplashScreen), true, true);
90
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetParent, (IntPtr)radApp.HWnd);
91
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllStepCount, 18);
92
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
93

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
515
                        SetFlowDirectionByLine(line.SPPID.ModelItemId);
516

    
517
                        ReleaseCOMObjects(modelItem);
518
                    }
519
                }
520

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

    
533
                SetFlowDirectionByLine(modelId);
534

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

    
548
                SetFlowDirectionByLine(modelId);
549

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

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

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

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

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

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

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

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

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

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

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

    
774
                LMDrawings drawings = new LMDrawings();
775
                drawings.Collect(dataSource, Filter: filter);
776

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

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

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

    
804
            List<string> drawingNameList = new List<string>();
805
            List<string> drawingNumberList = new List<string>();
806

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

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

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

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

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

    
878
            LMSymbol _LMSymbol = null;
879

    
880
            string mappingPath = symbol.SPPID.MAPPINGNAME;
881
            double x = symbol.SPPID.ORIGINAL_X;
882
            double y = symbol.SPPID.ORIGINAL_Y;
883
            int mirror = 0;
884
            double angle = symbol.ANGLE;
885

    
886
            // OPC 일경우 180도 일때 Mirror
887
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
888
                mirror = 1;
889

    
890
            // Mirror 계산
891
            if (symbol.FLIP == 1)
892
            {
893
                mirror = 1;
894
                angle += Math.PI;
895
            }
896

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

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

    
906
                if (_LMSymbol != null && _TargetItem != null)
907
                {
908
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
909

    
910
                    if (SPPIDUtil.IsSegmentLine(document, symbol, targetSymbol))
911
                    {
912
                        LMConnector reModelingConnector = FindBreakLineTarget(symbol, targetSymbol);
913
                        if (reModelingConnector != null)
914
                            ReModelingLMConnector(reModelingConnector);
915
                    }
916
                }
917

    
918
                ReleaseCOMObjects(_TargetItem);
919
            }
920
            else
921
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
922

    
923
            if (_LMSymbol != null)
924
            {
925
                _LMSymbol.Commit();
926

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

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

    
948

    
949
                }
950

    
951
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
952
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
953
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
954

    
955
                foreach (var item in symbol.ChildSymbols)
956
                    CreateChildSymbol(item, _LMSymbol, symbol);
957

    
958
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
959
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
960

    
961
                double[] range = null;
962
                GetSPPIDSymbolRange(symbol, ref range);
963
                symbol.SPPID.SPPID_Min_X = range[0];
964
                symbol.SPPID.SPPID_Min_Y = range[1];
965
                symbol.SPPID.SPPID_Max_X = range[2];
966
                symbol.SPPID.SPPID_Max_Y = range[3];
967

    
968
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
969
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
970
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
971
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
972

    
973
                ReleaseCOMObjects(_LMSymbol);
974
            }
975
        }
976

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

    
989
            symbol.SPPID.RepresentationId = string.Empty;
990
            symbol.SPPID.ModelItemID = string.Empty;
991
            symbol.SPPID.SPPID_X = double.NaN;
992
            symbol.SPPID.SPPID_Y = double.NaN;
993
            symbol.SPPID.SPPID_Min_X = double.NaN;
994
            symbol.SPPID.SPPID_Min_Y = double.NaN;
995
            symbol.SPPID.SPPID_Max_X = double.NaN;
996
            symbol.SPPID.SPPID_Max_Y = double.NaN;
997
        }
998

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

    
1013
                symbol.SPPID.RepresentationId = string.Empty;
1014
                symbol.SPPID.ModelItemID = string.Empty;
1015
                symbol.SPPID.SPPID_X = double.NaN;
1016
                symbol.SPPID.SPPID_Y = double.NaN;
1017
                symbol.SPPID.SPPID_Min_X = double.NaN;
1018
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1019
                symbol.SPPID.SPPID_Max_X = double.NaN;
1020
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1021
            }
1022
        }
1023

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

    
1035
            double[] range = null;
1036
            List<double[]> points = new List<double[]>();
1037
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1038
            double x1 = range[0];
1039
            double y1 = range[1];
1040
            double x2 = range[2];
1041
            double y2 = range[3];
1042

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

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

    
1060
            double percentX = (x2 - x1) / sizeWidth;
1061
            double percentY = (y2 - y1) / sizeHeight;
1062

    
1063
            double SPPIDgapX = gapX * percentX;
1064
            double SPPIDgapY = gapY * percentY;
1065

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

    
1081
            ReleaseCOMObjects(_TargetItem);
1082
        }
1083

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

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

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

    
1125
            foreach (var childSymbol in symbol.ChildSymbols)
1126
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1127

    
1128
            ReleaseCOMObjects(_TargetItem);
1129
        }
1130

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

    
1144
                foreach (var childSymbol in symbol.ChildSymbols)
1145
                    GetSPPIDChildSymbolRange(childSymbol, ref range);
1146

    
1147
                ReleaseCOMObjects(_TargetItem);
1148
            }
1149
        }
1150

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

    
1164
                tempRange[0] = Math.Min(tempRange[0], x1);
1165
                tempRange[1] = Math.Min(tempRange[1], y1);
1166
                tempRange[2] = Math.Max(tempRange[2], x2);
1167
                tempRange[3] = Math.Max(tempRange[3], y2);
1168

    
1169
                foreach (var childSymbol in symbol.ChildSymbols)
1170
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1171

    
1172
                ReleaseCOMObjects(_TargetItem);
1173
            }
1174

    
1175
            range = tempRange;
1176
        }
1177

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

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

    
1209
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1210
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1211

    
1212
                ReleaseCOMObjects(_ChildSymbol);
1213
            }
1214
        }
1215

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

    
1232
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1233
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1234
                ReleaseCOMObjects(_ChildSymbol);
1235
            }
1236
        }
1237

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

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

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

    
1275
                        //Leader 선 센터로
1276
                        if (_LMLabelPresist != null)
1277
                        {
1278
                            // Target Item에 Label의 Attribute Input
1279
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1280

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

    
1309
                                        if (result)
1310
                                            break;
1311
                                    }
1312

    
1313
                                    if (result)
1314
                                        break;
1315
                                }
1316
                            }
1317

    
1318
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1319
                            _LMLabelPresist.Commit();
1320
                            ReleaseCOMObjects(_LMLabelPresist);
1321
                        }
1322

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

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

    
1349
                    foreach (var item in connectorVertices)
1350
                        if (item.Key != null)
1351
                            ReleaseCOMObjects(item.Key);
1352
                }
1353
            }
1354
        }
1355

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

    
1365
            LMSymbol _LMSymbol = null;
1366
            LMSymbol targetItem = null;
1367
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1368
            double x = equipment.SPPID.ORIGINAL_X;
1369
            double y = equipment.SPPID.ORIGINAL_Y;
1370
            int mirror = 0;
1371
            double angle = equipment.ANGLE;
1372

    
1373
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1374

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

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

    
1411
            if (_LMSymbol != null)
1412
            {
1413
                _LMSymbol.Commit();
1414
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1415
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1416
                ReleaseCOMObjects(_LMSymbol);
1417
            }
1418

    
1419
            if (targetItem != null)
1420
            {
1421
                ReleaseCOMObjects(targetItem);
1422
            }
1423

    
1424
            ReleaseCOMObjects(_LMSymbol);
1425
        }
1426

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

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

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

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

    
1516
                                    // Range 겹치는지 확인해야함
1517
                                    double[] prevRange = null;
1518
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
1519
                                    double[] groupRange = null;
1520
                                    GetSPPIDSymbolRange(group, ref groupRange);
1521

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

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

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

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

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

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

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

    
1626

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

    
1635
            List<Line> group = new List<Line>();
1636
            GetConnectedLineGroup(line, group);
1637
            LineCoordinateCorrection(group);
1638

    
1639
            foreach (var groupLine in group)
1640
            {
1641
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
1642
                {
1643
                    BranchLines.Add(groupLine);
1644
                    continue;
1645
                }
1646

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

    
1720
                            placeRunInputs.AddPoint(x, y);
1721

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

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

    
1754
                    if (bRemodelingStart || bRemodelingEnd)
1755
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
1756

    
1757
                    FlowMarkModeling(groupLine);
1758
                    LineNumberModelingOnlyOne(groupLine);
1759

    
1760
                    ReleaseCOMObjects(_lMConnector);
1761
                }
1762
                else if (!isBranchModeling)
1763
                {
1764
                    Log.Write("Main Line Modeling : " + groupLine.UID);
1765
                }
1766

    
1767
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
1768
                x.ConnectedObject != null &&
1769
                x.ConnectedObject.GetType() == typeof(Line) &&
1770
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
1771
                .Select(x => x.ConnectedObject)
1772
                .ToList();
1773

    
1774
                foreach (var item in removeLines)
1775
                    RemoveLineForModeling(item as Line);
1776

    
1777
                if (_LMAItem != null)
1778
                    ReleaseCOMObjects(_LMAItem);
1779
                if (placeRunInputs != null)
1780
                    ReleaseCOMObjects(placeRunInputs);
1781
                if (_LMSymbolStart != null)
1782
                    ReleaseCOMObjects(_LMSymbolStart);
1783
                if (_LMSymbolEnd != null)
1784
                    ReleaseCOMObjects(_LMSymbolEnd);
1785

    
1786
                if (isBranchModeling && BranchLines.Contains(groupLine))
1787
                    BranchLines.Remove(groupLine);
1788
            }
1789
        }
1790

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

    
1819
                ReleaseCOMObjects(modelItem);
1820
            }
1821
        }
1822

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

    
1847
        private void LineCoordinateCorrection(List<Line> group)
1848
        {
1849
            // 순서대로 전 Item 기준 정렬
1850
            LineCoordinateCorrectionByStart(group);
1851

    
1852
            // 역으로 심볼이 있을 경우 좌표 보정
1853
            LineCoordinateCorrectionForLastLine(group);
1854
        }
1855

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

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

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

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

    
1910
                            double x = 0;
1911
                            double y = 0;
1912
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
1913
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
1914
                        }
1915
                        break;
1916
                    }
1917
                }
1918
            }
1919
        }
1920

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

    
1940
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
1941
        }
1942

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

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

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

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

    
2011
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2012
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2013
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2014

    
2015
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2016
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2017
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2018

    
2019
                if (startSpecBreak != null || startEndBreak != null)
2020
                    result = true;
2021
            }
2022
        }
2023

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

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

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

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

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

    
2112
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2113
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2114

    
2115
            ReleaseCOMObjects(placeRunInputs);
2116
            ReleaseCOMObjects(_LMAItem);
2117
            ReleaseCOMObjects(modelItem);
2118

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

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

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

    
2164
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2165
                ReleaseCOMObjects(newConnector);
2166
            }
2167

    
2168
            ReleaseCOMObjects(modelItem);
2169
        }
2170

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

    
2193
                    if (result)
2194
                        break;
2195
                }
2196
            }
2197
            foreach (var item in dicVertices)
2198
                ReleaseCOMObjects(item.Key);
2199
        }
2200

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

    
2226
                            if (child != null)
2227
                                break;
2228
                        }
2229

    
2230
                        if (child != null)
2231
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2232
                    }
2233

    
2234
                    break;
2235
                }
2236
            }
2237

    
2238
            return _LMSymbol;
2239
        }
2240

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

    
2257
            return null;
2258
        }
2259

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

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

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

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

    
2315
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2316
            {
2317
                double[] vertices = null;
2318
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2319
                double x = 0;
2320
                double y = 0;
2321
                lineStringGeometry.GetVertex(1, ref x, ref y);
2322

    
2323
                string flowDirection = string.Empty;
2324
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2325
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2326
                    flowDirection = flowAttribute.get_Value().ToString();
2327

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

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

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

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

    
2381
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
2382
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2383
                newConnector.Commit();
2384
                foreach (var line in lines)
2385
                    line.SPPID.ModelItemId = newConnector.ModelItemID;
2386
            }
2387

    
2388

    
2389
            return newConnector;
2390
        }
2391

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

    
2401
            if (upStreamObj != null &&
2402
                downStreamObj != null)
2403
            {
2404
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
2405

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

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

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

    
2450
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
2451
                {
2452
                    if (connector.get_ItemStatus() != "Active")
2453
                        continue;
2454

    
2455
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2456
                    {
2457
                        targetConnector = connector;
2458
                        break;
2459
                    }
2460
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2461
                    {
2462
                        targetConnector = connector;
2463
                        break;
2464
                    }
2465
                }
2466

    
2467
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
2468
                {
2469
                    if (connector.get_ItemStatus() != "Active")
2470
                        continue;
2471

    
2472
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
2473
                    {
2474
                        targetConnector = connector;
2475
                        break;
2476
                    }
2477
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
2478
                    {
2479
                        targetConnector = connector;
2480
                        break;
2481
                    }
2482
                }
2483

    
2484
                ReleaseCOMObjects(targetLMSymbol);
2485
                ReleaseCOMObjects(connectedLMSymbol);
2486
            }
2487
            else if (targetLine != null && connectedLine != null)
2488
            {
2489
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2490
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2491

    
2492
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
2493
                {
2494
                    foreach (LMRepresentation rep in targetModelItem.Representations)
2495
                    {
2496
                        if (targetConnector != null)
2497
                            break;
2498

    
2499
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2500
                        {
2501
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2502

    
2503
                            if (IsConnected(_LMConnector, connectedModelItem))
2504
                                targetConnector = _LMConnector;
2505
                            else
2506
                                ReleaseCOMObjects(_LMConnector);
2507
                        }
2508
                    }
2509

    
2510
                    ReleaseCOMObjects(targetModelItem);
2511
                }
2512
            }
2513
            else
2514
            {
2515
                LMSymbol connectedLMSymbol = null;
2516
                if (connectedSymbol != null)
2517
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
2518
                else if (targetSymbol != null)
2519
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
2520
                else
2521
                {
2522

    
2523
                }
2524
                LMModelItem targetModelItem = null;
2525
                if (targetLine != null)
2526
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
2527
                else if (connectedLine != null)
2528
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
2529
                else
2530
                {
2531

    
2532
                }
2533
                if (connectedLMSymbol != null && targetModelItem != null)
2534
                {
2535
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
2536
                    {
2537
                        if (connector.get_ItemStatus() != "Active")
2538
                            continue;
2539

    
2540
                        if (IsConnected(connector, targetModelItem))
2541
                        {
2542
                            targetConnector = connector;
2543
                            break;
2544
                        }
2545
                    }
2546

    
2547
                    if (targetConnector == null)
2548
                    {
2549
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
2550
                        {
2551
                            if (connector.get_ItemStatus() != "Active")
2552
                                continue;
2553

    
2554
                            if (IsConnected(connector, targetModelItem))
2555
                            {
2556
                                targetConnector = connector;
2557
                                break;
2558
                            }
2559
                        }
2560
                    }
2561
                }
2562

    
2563
            }
2564

    
2565
            return targetConnector;
2566
        }
2567

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

    
2585
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
2586

    
2587
                    ReleaseCOMObjects(modelItem);
2588
                    ReleaseCOMObjects(connectedConnector);
2589

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

    
2604
            return result;
2605
        }
2606

    
2607
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
2608
        {
2609
            bool result = false;
2610

    
2611
            foreach (LMRepresentation rep in modelItem.Representations)
2612
            {
2613
                if (result)
2614
                    break;
2615

    
2616
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2617
                {
2618
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2619

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

    
2653
                    ReleaseCOMObjects(_LMConnector);
2654
                }
2655
            }
2656

    
2657

    
2658
            return result;
2659
        }
2660

    
2661
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
2662
        {
2663
            foreach (LMRepresentation rep in modelItem.Representations)
2664
            {
2665
                if (connectedConnector != null)
2666
                    break;
2667

    
2668
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2669
                {
2670
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2671

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

    
2705
                    if (connectedConnector == null)
2706
                        ReleaseCOMObjects(_LMConnector);
2707
                }
2708
            }
2709
        }
2710

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

    
2725
                // item2가 item1으로 조인
2726
                _placement.PIDJoinRuns(ref item1, ref item2);
2727
                item1.Commit();
2728
                item2.Commit();
2729

    
2730
                string beforeID = string.Empty;
2731
                string afterID = string.Empty;
2732

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

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

    
2766
                ReleaseCOMObjects(modelItem1);
2767
                ReleaseCOMObjects(item1);
2768
                ReleaseCOMObjects(modelItem2);
2769
                ReleaseCOMObjects(item2);
2770
            }
2771
            catch (Exception ex)
2772
            {
2773
                Log.Write("Join Error");
2774
                Log.Write(ex.Message);
2775
            }
2776
        }
2777

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

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

    
2799

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

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

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

    
2856
                ReleaseCOMObjects(modelItem);
2857
            }
2858

    
2859
            return connectorVertices;
2860
        }
2861

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

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

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

    
2917
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
2918
                        if (length >= distance)
2919
                        {
2920
                            targetConnector = item.Key;
2921
                            length = distance;
2922
                        }
2923
                    }
2924
                }
2925
            }
2926

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

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

    
2947
            return targetConnector;
2948
        }
2949

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

    
2956
            double length = double.MaxValue;
2957
            LMConnector targetConnector = null;
2958
            double[] resultPoint = null;
2959
            List<double[]> targetVertices = null;
2960

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

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

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

    
2991
                    double maxLineX = Math.Max(point1[0], point2[0]);
2992
                    double minLineX = Math.Min(point1[0], point2[0]);
2993
                    double maxLineY = Math.Max(point1[1], point2[1]);
2994
                    double minLineY = Math.Min(point1[1], point2[1]);
2995

    
2996
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
2997

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

    
3034
            foreach (var item in vertices)
3035
                if (item.Key != null && item.Key != targetConnector)
3036
                    ReleaseCOMObjects(item.Key);
3037

    
3038
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3039
            {
3040
                double tempResultX = resultPoint[0];
3041
                double tempResultY = resultPoint[1];
3042
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3043

    
3044
                GridSetting gridSetting = GridSetting.GetInstance();
3045

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

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

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

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

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

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

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

    
3205
            x = resultPoint[0];
3206
            y = resultPoint[1];
3207

    
3208
            return targetConnector;
3209
        }
3210

    
3211
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
3212
        {
3213
            LMConnector result = null;
3214
            List<LMConnector> connectors = new List<LMConnector>();
3215
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3216

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

    
3225
                ReleaseCOMObjects(modelItem);
3226
            }
3227

    
3228
            if (connectors.Count == 1)
3229
                result = connectors[0];
3230
            else
3231
                foreach (var item in connectors)
3232
                    ReleaseCOMObjects(item);
3233

    
3234
            return result;
3235
        }
3236

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

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

    
3256
                    if (_LmLabelPresist != null)
3257
                    {
3258
                        _LmLabelPresist.Commit();
3259
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3260
                        ReleaseCOMObjects(_LmLabelPresist);
3261
                    }
3262
                }
3263
            }
3264
        }
3265

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

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

    
3282
                    if (_LmLabelPresist != null)
3283
                    {
3284
                        _LmLabelPresist.Commit();
3285
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
3286
                        ReleaseCOMObjects(_LmLabelPresist);
3287
                    }
3288
                }
3289

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

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

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

    
3385
                                        }
3386
                                    }
3387
                                }
3388
                                _LMModelItem.Commit();
3389
                            }
3390
                            if (_LMModelItem != null)
3391
                                ReleaseCOMObjects(_LMModelItem);
3392
                            endLine.Add(line.SPPID.ModelItemId);
3393
                        }
3394
                    }
3395
                }
3396
            }
3397
        }
3398

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

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

    
3447
                ReleaseCOMObjects(_Attributes);
3448
                ReleaseCOMObjects(_LMModelItem);
3449
                ReleaseCOMObjects(_LMSymbol);
3450
            }
3451
        }
3452

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

    
3462
            if (upStreamObj != null &&
3463
                downStreamObj != null)
3464
            {
3465
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3466

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

    
3484
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
3485
                                }
3486
                            }
3487
                        }
3488
                    }
3489

    
3490
                    ReleaseCOMObjects(targetLMConnector);
3491
                }
3492
            }
3493

    
3494

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

    
3515
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3516
                    {
3517
                        if (connector.get_ItemStatus() != "Active")
3518
                            continue;
3519

    
3520
                        if (connector.Id != zeroLenthConnector.Id)
3521
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3522
                    }
3523

    
3524
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3525
                    {
3526
                        if (connector.get_ItemStatus() != "Active")
3527
                            continue;
3528

    
3529
                        if (connector.Id != zeroLenthConnector.Id)
3530
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3531
                    }
3532

    
3533
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3534
                    {
3535
                        if (connector.get_ItemStatus() != "Active")
3536
                            continue;
3537

    
3538
                        if (connector.Id != zeroLenthConnector.Id)
3539
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3540
                    }
3541

    
3542
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3543
                    {
3544
                        if (connector.get_ItemStatus() != "Active")
3545
                            continue;
3546

    
3547
                        if (connector.Id != zeroLenthConnector.Id)
3548
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3549
                    }
3550

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

    
3561
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
3562
                    {
3563
                        if (connector.get_ItemStatus() != "Active")
3564
                            continue;
3565

    
3566
                        if (connector.Id == zeroLenthConnector.Id)
3567
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3568
                    }
3569

    
3570
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
3571
                    {
3572
                        if (connector.get_ItemStatus() != "Active")
3573
                            continue;
3574

    
3575
                        if (connector.Id == zeroLenthConnector.Id)
3576
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
3577
                    }
3578

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

    
3588
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
3589
                    {
3590
                        if (connector.get_ItemStatus() != "Active")
3591
                            continue;
3592

    
3593
                        if (connector.Id == zeroLenthConnector.Id)
3594
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3595
                    }
3596

    
3597
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
3598
                    {
3599
                        if (connector.get_ItemStatus() != "Active")
3600
                            continue;
3601

    
3602
                        if (connector.Id == zeroLenthConnector.Id)
3603
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
3604
                    }
3605

    
3606
                    ReleaseCOMObjects(zeroLenthConnector);
3607
                    ReleaseCOMObjects(downStreamLMSymbol);
3608
                }
3609
            }
3610

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

    
3625
                    _LMModelItem.Commit();
3626
                }
3627
                if (_LMModelItem != null)
3628
                    ReleaseCOMObjects(_LMModelItem);
3629
            }
3630

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

    
3645
                    _LMModelItem.Commit();
3646
                }
3647
                if (_LMModelItem != null)
3648
                    ReleaseCOMObjects(_LMModelItem);
3649
            }
3650
            #endregion
3651
        }
3652

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

    
3676
                            if (mapping != null)
3677
                            {
3678
                                double x = 0;
3679
                                double y = 0;
3680

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

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

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

    
3708
                            if (mapping != null)
3709
                            {
3710
                                double x = 0;
3711
                                double y = 0;
3712

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

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

    
3733
                double x = 0;
3734
                double y = 0;
3735
                double angle = text.ANGLE;
3736
                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
3737

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

    
3753
                            if (_LMAAttribute != null)
3754
                                ReleaseCOMObjects(_LMAAttribute);
3755
                            if (_LMItemNote != null)
3756
                                ReleaseCOMObjects(_LMItemNote);
3757
                        }
3758
                    }
3759
                }
3760
            }
3761
            if (_LMSymbol != null)
3762
                ReleaseCOMObjects(_LMSymbol);
3763
        }
3764

    
3765
        /// <summary>
3766
        /// Note Modeling
3767
        /// </summary>
3768
        /// <param name="note"></param>
3769
        private void NoteModeling(Note note)
3770
        {
3771
            LMSymbol _LMSymbol = null;
3772
            LMItemNote _LMItemNote = null;
3773
            LMAAttribute _LMAAttribute = null;
3774

    
3775
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
3776
            {
3777
                double x = 0;
3778
                double y = 0;
3779

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

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

    
3801
            if (_LMAAttribute != null)
3802
                ReleaseCOMObjects(_LMAAttribute);
3803
            if (_LMItemNote != null)
3804
                ReleaseCOMObjects(_LMItemNote);
3805
            if (_LMSymbol != null)
3806
                ReleaseCOMObjects(_LMSymbol);
3807
        }
3808

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

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

    
3872
                if (location.HasFlag(Location.Left))
3873
                    x = SPPIDLabelLocation.X1;
3874
                else if (location.HasFlag(Location.Right))
3875
                    x = SPPIDLabelLocation.X2;
3876

    
3877
                if (location.HasFlag(Location.Down))
3878
                    y = SPPIDLabelLocation.Y1;
3879
                else if (location.HasFlag(Location.Up))
3880
                    y = SPPIDLabelLocation.Y2;
3881
            }
3882
        }
3883

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

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

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

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

    
3921
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
3922
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
3923
                        symbols.Add(symbol);
3924
                }
3925
            }
3926

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

    
3937
            return symbols;
3938
        }
3939

    
3940
        private void SetPriorityLine(List<Line> lines)
3941
        {
3942
            lines.Sort(SortLinePriority);
3943

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

    
3979
                            }
3980
                        }
3981
                    }
3982
                }
3983

    
3984
                return 0;
3985
            }
3986

    
3987
            int CompareNotSegmentLine(Line a, Line b)
3988
            {
3989
                List<Connector> connectorsA = a.CONNECTORS
3990
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3991
                    .ToList();
3992

    
3993
                List<Connector> connectorsB = b.CONNECTORS
3994
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
3995
                    .ToList();
3996

    
3997
                // 오름차순
3998
                return connectorsB.Count.CompareTo(connectorsA.Count);
3999
            }
4000

    
4001
            int CompareConnSymbol(Line a, Line b)
4002
            {
4003
                List<Connector> connectorsA = a.CONNECTORS
4004
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4005
                    .ToList();
4006

    
4007
                List<Connector> connectorsB = b.CONNECTORS
4008
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
4009
                    .ToList();
4010

    
4011
                // 오름차순
4012
                return connectorsB.Count.CompareTo(connectorsA.Count);
4013
            }
4014

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

    
4023
                List<Connector> connectorsB = b.CONNECTORS
4024
                    .Where(conn => conn.ConnectedObject != null &&
4025
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
4026
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
4027
                    .ToList();
4028

    
4029
                // 오름차순
4030
                return connectorsB.Count.CompareTo(connectorsA.Count);
4031
            }
4032

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

    
4042
                // 내림차순
4043
                return connectorsA.Count.CompareTo(connectorsB.Count);
4044
            }
4045

    
4046
            int CompareNoneConn(Line a, Line b)
4047
            {
4048
                List<Connector> connectorsA = a.CONNECTORS
4049
                    .Where(conn => conn.ConnectedObject == null)
4050
                    .ToList();
4051

    
4052
                List<Connector> connectorsB = b.CONNECTORS
4053
                    .Where(conn => conn.ConnectedObject == null)
4054
                    .ToList();
4055

    
4056
                // 오름차순
4057
                return connectorsB.Count.CompareTo(connectorsA.Count);
4058
            }
4059
        }
4060

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

    
4071
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
4072
                 x.ConnectedObject.GetType() == typeof(Line) &&
4073
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
4074
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
4075

    
4076
                // 내림차순
4077
                return countA.CompareTo(countB);
4078
            }
4079
        }
4080

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

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

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

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

    
4138
                Thread.Sleep(milliseconds);
4139
            }
4140
        }
4141

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

    
4159
        /// IDisposable 구현
4160
        ~AutoModeling()
4161
        {
4162
            this.Dispose(false);
4163
        }
4164

    
4165
        private bool disposed;
4166
        public void Dispose()
4167
        {
4168
            this.Dispose(true);
4169
            GC.SuppressFinalize(this);
4170
        }
4171

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