/
rhinosdkdoc.cs
11031 lines (10158 loc) · 411 KB
/
rhinosdkdoc.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma warning disable 1591
#if RHINO_SDK
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Linq;
using Rhino.Geometry;
using Rhino.Display;
using Rhino.Collections;
using System.Collections.Generic;
using Rhino.DocObjects;
using Rhino.Render;
using Rhino.Render.PostEffects;
using Rhino.Runtime.InteropWrappers;
using Rhino.DocObjects.Tables;
using Rhino.FileIO;
using System.Diagnostics;
using Rhino.Render.CustomRenderMeshes;
namespace Rhino.Commands
{
/// <summary>
/// Argument package that is passed to a custom undo delegate
/// </summary>
public class CustomUndoEventArgs : EventArgs
{
internal CustomUndoEventArgs(Guid commandId, string description, bool createdByRedo, uint eventSn, object tag, RhinoDoc doc)
{
CommandId = commandId;
ActionDescription = description;
CreatedByRedo = createdByRedo;
UndoSerialNumber = eventSn;
Tag = tag;
Document = doc;
}
/// <since>5.0</since>
public Guid CommandId { get; }
/// <since>5.0</since>
[CLSCompliant(false)]
public uint UndoSerialNumber { get; }
/// <since>5.0</since>
public string ActionDescription { get; }
/// <since>5.0</since>
public bool CreatedByRedo { get; }
/// <since>5.0</since>
public object Tag { get; }
/// <since>5.0</since>
public RhinoDoc Document { get; }
}
}
namespace Rhino
{
class CustomUndoCallback
{
public CustomUndoCallback(uint serialNumber, EventHandler<Commands.CustomUndoEventArgs> handler, object tag, string description, RhinoDoc document)
{
Handler = handler;
SerialNumber = serialNumber;
Tag = tag;
Description = description;
Document = document;
}
public uint SerialNumber { get; }
public EventHandler<Commands.CustomUndoEventArgs> Handler { get; }
public object Tag { get; }
public RhinoDoc Document { get; }
public string Description { get; }
}
namespace Render
{
public class ImageFileEventArgs : EventArgs
{
internal ImageFileEventArgs(
ImageFileEvent eventType,
string fileName,
string renderEngine,
Guid renderEngineId,
Guid sessionId,
int ellapsedTime)
{
Event = eventType;
FileName = fileName;
RenderEngine = renderEngine;
RenderEngineId = renderEngineId;
SessionId = sessionId;
EllapsedTime = ellapsedTime;
}
/// <since>5.11</since>
public ImageFileEvent Event { get; private set; }
/// <since>5.11</since>
public string FileName { get; private set; }
/// <since>5.11</since>
public string RenderEngine { get; private set; }
/// <since>5.11</since>
public Guid RenderEngineId { get; private set; }
/// <since>5.11</since>
public Guid SessionId { get; private set; }
/// <since>5.11</since>
public int EllapsedTime { get; private set; }
}
/// <since>5.11</since>
public enum ImageFileEvent
{
/// <summary>
/// Render image file has been successfully written
/// </summary>
Saved,
/// <summary>
/// Render image file has been successfully loaded
/// </summary>
Loaded,
/// <summary>
/// Render image file was just deleted
/// </summary>
Deleted,
}
/// <summary>
/// Controls interaction with RDK render image files
/// </summary>
public static class ImageFile
{
/// <summary>
/// Render image file saved, happens when a rendering completes.
/// If a plug-in needs to save additional file information it should
/// write it to the same folder as the Rhino render image file. Rhino
/// will take care of deleting old data.
/// </summary>
/// <since>5.11</since>
public static event EventHandler<ImageFileEventArgs> Saved
{
add
{
OnAddEvent();
SavedEvent -= value;
SavedEvent += value;
}
remove
{
SavedEvent -= value;
OnRemoveEvent();
}
}
private static event EventHandler<ImageFileEventArgs> SavedEvent;
/// <summary>
/// Generally called when the "RenderOpenLastRender" command is run,
/// this event is raised after the render window has been created and the
/// saved scene has been loaded.
/// </summary>
/// <since>5.11</since>
public static event EventHandler<ImageFileEventArgs> Loaded
{
add
{
OnAddEvent();
LoadedEvent -= value;
LoadedEvent += value;
}
remove
{
LoadedEvent -= value;
OnRemoveEvent();
}
}
private static event EventHandler<ImageFileEventArgs> LoadedEvent;
/// <summary>
/// Called when the RDK is cleaning up old render image files, a
/// plug-in should delete any plug-in specific image files at this
/// time.
/// </summary>
/// <since>5.11</since>
public static event EventHandler<ImageFileEventArgs> Deleted
{
add
{
OnAddEvent();
DeletedEvent -= value;
DeletedEvent += value;
}
remove
{
DeletedEvent -= value;
OnRemoveEvent();
}
}
private static event EventHandler<ImageFileEventArgs> DeletedEvent;
private static void OnAddEvent()
{
if (g_on_render_image_event != null)
return;
lock (g_event_lock)
{
g_on_render_image_event = OnRenderImageEvent;
UnsafeNativeMethods.CRdkCmnEventWatcher_SetOnRenderImageEventCallback(
g_on_render_image_event,
Runtime.HostUtils.m_rdk_ew_report);
}
}
private static void OnRemoveEvent()
{
if (g_on_render_image_event == null || SavedEvent != null || LoadedEvent != null || DeletedEvent != null)
return;
lock (g_event_lock)
{
UnsafeNativeMethods.CRdkCmnEventWatcher_SetOnRenderImageEventCallback(null, Runtime.HostUtils.m_rdk_ew_report);
g_on_render_image_event = null;
}
}
private static readonly object g_event_lock = new object();
internal delegate void OnRenderImageCallback(UnsafeNativeMethods.OnRenderingEventType eventType, IntPtr args);
private static OnRenderImageCallback g_on_render_image_event;
private static void OnRenderImageEvent(UnsafeNativeMethods.OnRenderingEventType eventType, IntPtr args)
{
var event_id = ImageFileEvent.Saved;
// Convert the unmanaged event UUID to a RenderHistoryEvent value and bail
// if the event callback has not been set
switch (eventType)
{
case UnsafeNativeMethods.OnRenderingEventType.Saved:
if (SavedEvent == null)
return; // No events registered so bail
break;
case UnsafeNativeMethods.OnRenderingEventType.Loaded:
if (LoadedEvent == null)
return; // No events registered so bail
event_id = ImageFileEvent.Loaded;
break;
case UnsafeNativeMethods.OnRenderingEventType.Deleted:
if (DeletedEvent == null)
return; // No events registered so bail
event_id = ImageFileEvent.Deleted;
break;
default:
throw new Exception("Unknown OnRenderingEventType");
}
// Get the unmanaged history event arguments
using (var file_name_string_holder = new StringHolder())
using (var render_engine_string_holder = new StringHolder())
{
var file_name_pointer = file_name_string_holder.NonConstPointer();
var render_engine_pointer = render_engine_string_holder.NonConstPointer();
var render_engine = Guid.Empty;
var session_id = Guid.Empty;
var elapsed_time = 0; // Legacy.
var sta_time_ms = (ulong)0;
var end_time_ms = (ulong)0;
UnsafeNativeMethods.CRdkCmnEventWatcher_GetRenderingFileInfoArgs(
args,
file_name_pointer,
render_engine_pointer,
ref render_engine,
ref session_id,
ref elapsed_time,
ref sta_time_ms,
ref end_time_ms);
// Data passed to the Rhino Common event
var event_args = new ImageFileEventArgs(
event_id,
file_name_string_holder.ToString(),
render_engine_string_holder.ToString(),
render_engine,
session_id,
elapsed_time
// sta_time_ms, // TODO: [MAXLOOK] Not sure if it would break the SDK.
// end_time_ms, // TODO:
);
// Raise the event in RhinoCommon
switch (event_id)
{
case ImageFileEvent.Saved:
SavedEvent.Invoke(null, event_args);
break;
case ImageFileEvent.Loaded:
LoadedEvent.Invoke(null, event_args);
break;
case ImageFileEvent.Deleted:
DeletedEvent.Invoke(null, event_args);
break;
}
}
}
}
}
/// <summary>
/// Represents an active model.
/// </summary>
public sealed class RhinoDoc : IDisposable
{
#region statics
/// <summary>
/// Do not make this public; it is used for legacy functions that assumed
/// an ActiveDoc. This gives me a single location to fix things since I
/// can probably figure out a "scoped" document in many cases
/// </summary>
/// <param name="tolerance"></param>
/// <param name="angleTolerance"></param>
internal static void ActiveDocTolerances(out double tolerance, out double angleTolerance)
{
// 16 May 2013 - S. Baer
// Dale Lear recommends that we always use constant tolerance values for the
// deprecated functions that used ActiveDoc tolerances.
tolerance = 0.001;
angleTolerance = 0.5 * Math.PI / 180.0;
}
/// <summary>
/// Opens a 3dm file and makes it the active document. If called on
/// windows the active document will be saved and closed and the new
/// document will be opened and become the active document. If called
/// on the Mac the file will be opened in a new document window.
/// </summary>
/// <param name="filePath">Full path to the 3dm file to open</param>
/// <param name="wasAlreadyOpen">
/// Will get set to true if there is a currently open document with the
/// specified path; otherwise it will get set to false.
/// </param>
/// <returns>
/// Returns the newly opened document on success or null on error.
/// </returns>
/// <since>6.0</since>
public static RhinoDoc Open(string filePath, out bool wasAlreadyOpen)
{
wasAlreadyOpen = (null != FromFilePath(filePath));
if (string.IsNullOrWhiteSpace(filePath))
return null;
if (!System.IO.File.Exists(filePath))
return null;
if (!UnsafeNativeMethods.CRhinoFileMenu_Open(filePath))
return null;
var doc = FromFilePath(filePath);
return doc;
}
/// <summary>
/// Search the open document list for a document with a Path equal
/// to the specified file path.
/// </summary>
/// <returns>The file name to search for</returns>
/// <param name="filePath">The full path to the file to search for.</param>
/// <since>6.0</since>
public static RhinoDoc FromFilePath(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
return null;
var open_docs = OpenDocuments(true);
foreach (var doc in open_docs)
{
var path = doc == null ? string.Empty : doc.Path;
if (filePath.Equals(path, StringComparison.Ordinal))
return doc;
}
return null;
}
/// <since>5.0</since>
/// <deprecated>6.0</deprecated>
[Obsolete("OpenFile is obsolete, use Open instead")]
public static bool OpenFile(string path)
{
return UnsafeNativeMethods.CRhinoFileMenu_Open(path);
}
/// <since>5.0</since>
public static bool ReadFile(string path, FileReadOptions options)
{
if (ActiveDoc == null)
return false;
IntPtr const_ptr_options = options.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoReadFile(ActiveDoc.RuntimeSerialNumber, path, const_ptr_options);
}
#endregion
/// <summary>
/// MAC ONLY, always returns false on Windows.
/// Check to see if this document is in the process of being reverted
/// indicating it will get closed when the revert is completed.
/// </summary>
/// <returns>
/// MAC ONLY, always returns false on Windows.
/// Returns true if running on Mac and the document is being reverted to a
/// previous revision.
/// </returns>
internal bool IsReverting => UnsafeNativeMethods.CRhinoDoc_IsReverting(RuntimeSerialNumber);
/// <since>7.0</since>
public bool IsHeadless => UnsafeNativeMethods.CRhinoDoc_IsHeadless(RuntimeSerialNumber) != 0;
/// <since>7.0</since>
public void Dispose()
{
if (!IsHeadless)
return; // Managed by Rhino
if (RuntimeSerialNumber == 0)
return; // Already disposed
var activeDoc = ActiveDoc;
bool changeActiveDoc = false;
if (activeDoc != null && activeDoc.RuntimeSerialNumber == this.RuntimeSerialNumber)
changeActiveDoc = true;
GC.SuppressFinalize(this);
UnsafeNativeMethods.CRhinoDoc_Delete(RuntimeSerialNumber);
RuntimeSerialNumber = 0;
if( changeActiveDoc )
{
RhinoDoc[] docs = OpenDocuments();
if (docs.Length > 0)
ActiveDoc = docs[0];
}
}
~RhinoDoc()
{
Debug.Assert(IsHeadless);
if (!RhinoApp.IsRunningHeadless)
{
EventHandler FinalizeOnUIThread = null;
RhinoApp.Idle += FinalizeOnUIThread = (sender, args) =>
{
RhinoApp.Idle -= FinalizeOnUIThread;
// Destroy the object in UI thread if we are not in Headless mode
UnsafeNativeMethods.CRhinoDoc_Delete(RuntimeSerialNumber);
};
}
else
{
// Destroy the object here if we are in Headless mode
UnsafeNativeMethods.CRhinoDoc_Delete(RuntimeSerialNumber);
}
}
#region IO Methods
/// <summary>
/// Create a new headless RhinoDoc from a template file
/// </summary>
/// <param name="file3dmTemplatePath">
/// Name of a Rhino model to use as a template to initialize the document.
/// If null, an empty document is created
/// </param>
/// <returns>
/// New RhinoDoc on success. Note that this is a "headless" RhinoDoc and it's
/// lifetime is under your control.
/// </returns>
/// <since>7.0</since>
public static RhinoDoc CreateHeadless(string file3dmTemplatePath)
{
// This line checks filePath is a valid path, well formatted, not too long...
if (!string.IsNullOrWhiteSpace(file3dmTemplatePath))
{
var info = new System.IO.FileInfo(file3dmTemplatePath);
if (string.Compare(info.Extension, ".3DM", true) != 0)
throw new ArgumentException("Template file path should have a 3DM extension", "file3DMTemplatePath");
}
uint serial_number = UnsafeNativeMethods.CRhinoDoc_New(file3dmTemplatePath);
return RhinoDoc.FromRuntimeSerialNumber(serial_number);
}
/// <summary>
/// Opens a 3DM file into a new headless RhinoDoc.
/// </summary>
/// <param name="file3dmPath">
/// Path of a Rhino model to load.
/// </param>
/// <returns></returns>
/// <since>7.0</since>
public static RhinoDoc OpenHeadless(string file3dmPath)
{
// This line checks filePath is a valid path, well formatted, not too long...
if (file3dmPath != null)
{
var info = new System.IO.FileInfo(file3dmPath);
if (string.Compare(info.Extension, ".3DM", true) != 0)
throw new ArgumentException("Source file path should have a 3DM extension", "file3DMPath");
}
uint serial_number = UnsafeNativeMethods.CRhinoDoc_Load(file3dmPath);
return RhinoDoc.FromRuntimeSerialNumber(serial_number);
}
/// <summary>
/// Import geometry into a RhinoDoc from a file. This can be any file format
/// that Rhino can import
/// </summary>
/// <param name="filePath"></param>
/// <returns>true on success</returns>
/// <since>7.0</since>
public bool Import(string filePath)
{
return Import(filePath, null);
}
/// <summary>
/// Import geometry into a RhinoDoc from a file. This can be any file format
/// that Rhino can import
/// </summary>
/// <param name="filePath"></param>
/// <param name="options"></param>
/// <returns></returns>
/// <exception cref="System.IO.FileNotFoundException"></exception>
/// <since>8.0</since>
public bool Import(string filePath, ArchivableDictionary options)
{
// This line checks filePath is a valid path, well formatted, not too long...
var fileInfo = new System.IO.FileInfo(filePath);
if (!fileInfo.Exists)
throw new System.IO.FileNotFoundException(string.Empty, filePath);
using
(
var readOptions = new FileReadOptions()
{
ImportMode = true,
BatchMode = true,
UseScaleGeometry = true,
ScaleGeometry = true
}
)
{
if (options!=null)
{
readOptions.OptionsDictionary.AddContentsFrom(options);
}
IntPtr const_ptr_options = readOptions.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoReadFile(RuntimeSerialNumber, filePath, const_ptr_options);
}
}
/// <summary>
/// Save doc to disk using the document's Path
/// </summary>
/// <returns></returns>
/// <since>7.0</since>
public bool Save()
{
if (string.IsNullOrEmpty(Path))
throw new InvalidOperationException("RhinoDoc.Path has no value.");
using
(
var options = new FileWriteOptions()
{
UpdateDocumentPath = true,
SuppressAllInput = true,
SuppressDialogBoxes = true,
WriteSelectedObjectsOnly = false,
}
)
{
IntPtr const_ptr_options = options.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoWrite3dmFile(RuntimeSerialNumber, Path, const_ptr_options);
}
}
//public bool SaveIncremental()
// 20 June 2019 S. Baer
// Making private for now. I would like to figure out why we have a version parameter here.
bool SaveSmall(int version = 0)
{
if (string.IsNullOrEmpty(Path))
throw new InvalidOperationException("RhinoDoc.Path has no value.");
using
(
var options = new FileWriteOptions()
{
UpdateDocumentPath = true,
SuppressAllInput = true,
SuppressDialogBoxes = true,
WriteSelectedObjectsOnly = false,
WriteGeometryOnly = true,
FileVersion = version
}
)
{
IntPtr const_ptr_options = options.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoWrite3dmFile(RuntimeSerialNumber, Path, const_ptr_options);
}
}
/// <summary>
/// Save doc as a 3dm to a specified path using the current Rhino file version
/// </summary>
/// <param name="file3dmPath"></param>
/// <returns>true on success</returns>
/// <since>7.0</since>
public bool SaveAs(string file3dmPath)
{
return SaveAs(file3dmPath, 0);
}
/// <summary>
/// Save doc as a 3dm to a specified path
/// </summary>
/// <param name="file3dmPath"></param>
/// <param name="version">Rhino file version</param>
/// <returns>true on success</returns>
/// <since>7.0</since>
public bool SaveAs(string file3dmPath, int version)
{
return SaveAs(file3dmPath, version, true, true, true, true);
}
/// <summary>
/// Save doc as a 3dm to a specified path
/// </summary>
/// <param name="file3dmPath"></param>
/// <param name="version">Rhino file version</param>
/// <param name="saveSmall">whether to inlcude render meshes and preview image</param>
/// <param name="saveTextures">whether to include the bitmap table</param>
/// <param name="saveGeometryOnly">whether to write enything besides geometry</param>
/// <param name="savePluginData">whether to write plugin user data</param>
/// <returns>true on success</returns>
/// <since>8.0</since>
public bool SaveAs(string file3dmPath, int version, bool saveSmall, bool saveTextures, bool saveGeometryOnly, bool savePluginData)
{
// This line checks filePath is a valid path, well formatted, not too long...
var info = new System.IO.FileInfo(file3dmPath);
if (string.Compare(info.Extension, ".3DM", true) != 0)
throw new ArgumentException("Destination file path should have a 3DM extension", "file3DMPath");
using
(
var options = new FileWriteOptions()
{
UpdateDocumentPath = true,
SuppressAllInput = true,
SuppressDialogBoxes = true,
WriteSelectedObjectsOnly = false,
FileVersion = version,
IncludeRenderMeshes = !saveSmall,
IncludePreviewImage = !saveSmall,
IncludeBitmapTable = saveTextures,
WriteGeometryOnly = saveGeometryOnly,
WriteUserData = savePluginData
}
)
{
IntPtr const_ptr_options = options.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoWrite3dmFile(RuntimeSerialNumber, file3dmPath, const_ptr_options);
}
}
/// <summary>
/// Save this document as a template
/// </summary>
/// <param name="file3dmTemplatePath"></param>
/// <returns>true on success</returns>
/// <since>7.0</since>
public bool SaveAsTemplate(string file3dmTemplatePath)
{
return SaveAsTemplate(file3dmTemplatePath, 0);
}
/// <summary>
/// Save this document as a template to a specific Rhino file version
/// </summary>
/// <param name="file3dmTemplatePath"></param>
/// <param name="version"></param>
/// <returns>true on success</returns>
/// <since>7.0</since>
public bool SaveAsTemplate(string file3dmTemplatePath, int version)
{
// This line checks filePath is a valid path, well formatted, not too long...
var info = new System.IO.FileInfo(file3dmTemplatePath);
if (string.Compare(info.Extension, ".3DM", true) != 0)
throw new ArgumentException("Destination file path should have a 3DM extension", "file3DMTemplatePath");
using
(
var options = new FileWriteOptions()
{
UpdateDocumentPath = false,
SuppressAllInput = true,
SuppressDialogBoxes = true,
WriteSelectedObjectsOnly = false,
FileVersion = version
}
)
{
IntPtr const_ptr_options = options.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoWrite3dmFile(RuntimeSerialNumber, file3dmTemplatePath, const_ptr_options);
}
}
/// <summary>
/// Export the entire document to a file. All file formats that Rhino can export to
/// are supported by this function.
/// </summary>
/// <param name="filePath"></param>
/// <returns>true on success</returns>
/// <since>7.0</since>
public bool Export(string filePath)
{
ArchivableDictionary dict = null;
return Export(filePath, dict);
}
/// <summary>
/// Export the entire document to a file. All file formats that Rhino can export to
/// are supported by this function.
/// </summary>
/// <param name="filePath"></param>
/// <param name="options">
/// Options to help define how data should be exported.
/// </param>
/// <returns>true on success</returns>
/// <since>8.0</since>
public bool Export(string filePath, ArchivableDictionary options)
{
// This line checks filePath is a valid path, well formatted, not too long...
new System.IO.FileInfo(filePath);
using
(
var fileWriteOptions = new FileWriteOptions()
{
UpdateDocumentPath = false,
SuppressAllInput = true,
SuppressDialogBoxes = true,
WriteSelectedObjectsOnly = false,
}
)
{
if (options != null)
{
fileWriteOptions.OptionsDictionary.AddContentsFrom(options);
}
IntPtr const_ptr_options = fileWriteOptions.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoWriteFile(RuntimeSerialNumber, filePath, const_ptr_options);
}
}
/// <summary>
/// Export selected geometry to a file. All file formats that Rhino can export
/// to are supported by this function.
/// </summary>
/// <param name="filePath"></param>
/// <returns>true on success</returns>
/// <since>7.0</since>
public bool ExportSelected(string filePath)
{
ArchivableDictionary dict = null;
return ExportSelected(filePath, dict);
}
/// <summary>
/// Export selected geometry to a file. All file formats that Rhino can export
/// to are supported by this function.
/// </summary>
/// <param name="filePath"></param>
/// <param name="options">
/// Options to help define how data should be exported.
/// </param>
/// <returns>true on success</returns>
/// <since>8.0</since>
public bool ExportSelected(string filePath, ArchivableDictionary options)
{
// This line checks filePath is a valid path, well formatted, not too long...
new System.IO.FileInfo(filePath);
using
(
var fileWriteOptions = new FileWriteOptions()
{
UpdateDocumentPath = false,
SuppressAllInput = true,
SuppressDialogBoxes = true,
WriteSelectedObjectsOnly = true,
}
)
{
if (options!=null)
{
fileWriteOptions.OptionsDictionary.AddContentsFrom(options);
}
IntPtr const_ptr_options = fileWriteOptions.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoWriteFile(RuntimeSerialNumber, filePath, const_ptr_options);
}
}
//public bool ExportWithOrigin(string filePath, Point3d Origin)
/// <summary>
/// Write information in this document to a file.
/// Note, the active document's name will be changed to that
/// of the path provided.
/// </summary>
/// <param name="path">The name of the file to write.</param>
/// <param name="options">The file writing options.</param>
/// <returns>true if successful, false on failure.</returns>
/// <remarks>
/// This is the best choice for general file writing.
/// It handles making backups using temporary files,
/// locking and unlocking, loading file writing plug-ins,
/// and many other details.
/// </remarks>
/// <since>5.0</since>
public bool WriteFile(string path, FileWriteOptions options)
{
IntPtr const_ptr_options = options.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoWriteFile(RuntimeSerialNumber, path, const_ptr_options);
}
/// <summary>
/// Write information in this document to a .3dm file.
/// Note, the active document's name will not be changed.
/// </summary>
/// <param name="path">The name of the .3dm file to write.</param>
/// <param name="options">The file writing options.</param>
/// <returns>true if successful, false on failure.</returns>
/// <since>6.5</since>
public bool Write3dmFile(string path, FileWriteOptions options)
{
IntPtr const_ptr_options = options.ConstPointer(true);
return UnsafeNativeMethods.RHC_RhinoWrite3dmFile(RuntimeSerialNumber, path, const_ptr_options);
}
#endregion
/// <summary>
/// Search for a file using Rhino's search path. Rhino will look in the
/// following places:
/// 1. Current model folder
/// 2. Path specified in options dialog/File tab
/// 3. Rhino system folders
/// 4. Rhino executable folder
/// </summary>
/// <param name="filename"></param>
/// <returns>
/// Path to existing file if found, an empty string if no file was found
/// </returns>
/// <since>5.0</since>
public string FindFile(string filename)
{
using (var sh = new StringHolder())
{
IntPtr ptr_string = sh.NonConstPointer();
UnsafeNativeMethods.CRhinoFileUtilities_FindFile(filename, ptr_string);
return sh.ToString();
}
}
private RhinoDoc(uint serialNumber)
{
// cast to int until I can get all of the other calls to m_runtime_serial_number switched over
RuntimeSerialNumber = serialNumber;
if (!IsHeadless)
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a new RhinoDoc
/// </summary>
/// <param name="modelTemplateFileName">
/// Name of a Rhino model to use as a template to initialize the document.
/// If the template contains views, those views are created.
/// If null, an empty document with no views is created
/// </param>
/// <returns></returns>
/// <since>6.4</since>
public static RhinoDoc Create(string modelTemplateFileName)
{
uint serial_number = UnsafeNativeMethods.CRhinoDoc_Create(modelTemplateFileName);
return RhinoDoc.FromRuntimeSerialNumber(serial_number);
}
/// <summary>
/// Returns a list of currently open Rhino documents
/// </summary>
/// <returns></returns>
/// <since>6.0</since>
public static RhinoDoc[] OpenDocuments()
{
return OpenDocuments(false);
}
/// <summary>
/// Returns a list of currently open Rhino documents
/// </summary>
/// <param name="includeHeadless">pass true to include headless docs in the list</param>
/// <returns></returns>
/// <since>7.2</since>
public static RhinoDoc[] OpenDocuments(bool includeHeadless)
{
var list = new List<RhinoDoc>();
var iterator = UnsafeNativeMethods.CRhinoDocIterator_New(includeHeadless);
if (iterator != IntPtr.Zero)
{
try
{
for (var sn = UnsafeNativeMethods.RhinoDocIterator_FirstOrNext(iterator, 1); sn > 0; sn = UnsafeNativeMethods.RhinoDocIterator_FirstOrNext(iterator, 0))
{
var doc = RhinoDoc.FromRuntimeSerialNumber(sn);
if (doc != null)
list.Add(doc);
}
}
finally
{
UnsafeNativeMethods.CRhinoDocIterator_Delete(iterator);
}
}
return list.ToArray();
}
/// <summary>
/// WARNING!! Do not use the ActiveDoc if you don't have to. Under Mac Rhino the ActiveDoc
/// can change while a command is running. Use the doc that is passed to you in your RunCommand
/// function or continue to use the same doc after the first call to ActiveDoc.
/// </summary>
/// <since>5.0</since>
public static RhinoDoc ActiveDoc
{
get
{
uint id = UnsafeNativeMethods.CRhinoDoc_ActiveDocId();
return FromRuntimeSerialNumber(id);
}
set
{
uint serialNumber = 0;
if( value!=null )
serialNumber = value.RuntimeSerialNumber;
UnsafeNativeMethods.CRhinoDoc_MakeActive(serialNumber);
}
}
/// <since>5.0</since>
/// <deprecated>6.0</deprecated>
[Obsolete("Use FromRuntimeSerialNumber")]
public static RhinoDoc FromId(int docId)
{
if( docId<0 )
return null;
return FromRuntimeSerialNumber((uint)docId);
}
static int HeadlessDocumentCountOnLastCull = 0;
/// <since>6.0</since>
[CLSCompliant(false)]
public static RhinoDoc FromRuntimeSerialNumber(uint serialNumber)
{
if (serialNumber == 0)
return null;
RhinoDoc value = null;
int headless = UnsafeNativeMethods.CRhinoDoc_IsHeadless(serialNumber);
if (headless == 1)
{
lock (HeadlessDocuments)
{
if (HeadlessDocuments.TryGetValue(serialNumber, out WeakReference<RhinoDoc> reference))
{
reference.TryGetTarget(out value);
// if 'value' is null here means the object is collected
}
else
{
value = new RhinoDoc(serialNumber);
HeadlessDocuments[serialNumber] = new WeakReference<RhinoDoc>(value);
}
// If we have more than 1/8 potential garbage entries we try to cull those entries
if (HeadlessDocuments.Count - HeadlessDocumentCountOnLastCull > HeadlessDocuments.Count / 8)
{
// Remove collected entries
foreach (var key in HeadlessDocuments.Where(x => !x.Value.TryGetTarget(out RhinoDoc doc)).Select(x => x.Key).ToArray())