/
DirectShape.cs
468 lines (396 loc) · 18.1 KB
/
DirectShape.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
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Autodesk.DesignScript.Geometry;
using Autodesk.DesignScript.Runtime;
using Autodesk.Revit.DB;
using Revit.GeometryConversion;
using RevitServices.Materials;
using RevitServices.Persistence;
using RevitServices.Transactions;
namespace Revit.Elements
{
/// <summary>
/// This class acts as a representation of a directShape state, we can store it in trace
/// and on protogeometry types (in their tags dictionary) to keep track of the state of
/// a DirectShape wrapper type, it inherits from SerializeableId so that ElementLifeCycle
/// and DocumentEvents continue to function for DirectShapes.
/// </summary>
[SupressImportIntoVM]
[Serializable]
public class DirectShapeState : SerializableId
{
public string syncId { get; set; }
public long materialId { get; set; }
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("syncId", syncId, typeof(string));
info.AddValue("materialId", materialId, typeof(int));
}
public DirectShapeState(DirectShape ds, string syncId, ElementId materialId) :
base()
{
this.IntID = ds.InternalElement.Id.Value;
this.StringID = ds.UniqueId;
this.syncId = syncId;
this.materialId = materialId.Value;
}
public DirectShapeState(SerializationInfo info, StreamingContext context) :
base(info, context)
{
syncId = (string)info.GetValue("syncId", typeof(string));
materialId = (int)info.GetValue("materialId", typeof(int));
}
}
/// <summary>
/// A Revit DirectShape, which is a wrapper for some other geometrical entities
/// </summary>
[DynamoServices.RegisterForTrace]
public class DirectShape : Element
{
private const string DEFAULT_NAME = "DirectShape";
#region Static Fields
private static Guid DYNAMO_DIRECTSHAPE_APP_GUID;
#endregion
#region Public Static Properties
[IsVisibleInDynamoLibrary(false)]
public static Material DynamoPreviewMaterial { get; private set; }
#endregion
#region Internal Properties
internal Autodesk.Revit.DB.DirectShape InternalDirectShape
{
get;
private set;
}
/// <summary>
/// Reference to the Element
/// </summary>
public override Autodesk.Revit.DB.Element InternalElement
{
get { return InternalDirectShape; }
}
#endregion
#region Private constructors
/// <summary>
/// Wrap an existing DirectShape.
/// </summary>
/// <param name="shape"></param>
protected DirectShape(Autodesk.Revit.DB.DirectShape shape)
{
SafeInit(() => InitDirectShape(shape), true);
}
/// <summary>
/// Internal Constructor for a new DirectShape
/// </summary>
protected DirectShape(DesignScriptEntity shapeReference, string shapename, Category category, Material material)
{
SafeInit(() => InitDirectShape(shapeReference, shapename, category, material));
}
/// <summary>
/// Initialize a DirectShape element
/// </summary>
private void InitDirectShape(Autodesk.Revit.DB.DirectShape shape)
{
InternalSetDirectShape(shape);
}
/// <summary>
/// Initialize a DirectShape element
/// </summary>
private void InitDirectShape(DesignScriptEntity shapeReference,
string shapeName,
Category category,
Material material)
{
//Phase 1 - Check to see if a DirectShape exists in trace and should be rebound
var oldShape =
ElementBinder.GetElementAndTraceData<Autodesk.Revit.DB.DirectShape, DirectShapeState>(Document);
//There was a oldDirectShape, rebind to that
if (oldShape != null)
{
//set the directshape element
this.InternalSetDirectShape(oldShape.Item1);
//if the cateogryID has changed, we cannot continue to rebind and instead
//will make a new directShape
if (category.Id == this.InternalElement.Category.Id.Value)
{
//set the shape geometry of the directshape, this method passes in the actual input geo
//and checks the directShapeState object at the elementId key in the input geo tags dictionary.
//this check is used to determine if the geometry should be updated, this is done by checking
//the sync guid in the DirectShapeState (a guid that is generated when geometry changes on
//the revit element.
//we also check the material, if it's different than the currently assigned material
//then we need to rebuild the geo so that a new material is applied
//
this.InternalSetShape(shapeReference, new ElementId(material.Id), oldShape.Item2.syncId);
this.InternalSetName(shapeReference, shapeName, material, category);
return;
}
}
//Phase 2- There was no existing shape, create one
TransactionManager.Instance.EnsureInTransaction(Document);
Autodesk.Revit.DB.DirectShape ds;
//generate the geometry correctly depending on the type of geo
var tessellatedShape = GenerateTessellatedGeo(shapeReference, new ElementId(material.Id));
//actually construct the directshape revit element
ds = NewDirectShape(tessellatedShape,
Document, new ElementId(category.Id),
DirectShape.DYNAMO_DIRECTSHAPE_APP_GUID.ToString(), shapeName);
InternalSetDirectShape(ds);
InternalSetName(shapeReference, shapeName, material, category);
//generate a new syncId for trace
var traceData = new DirectShapeState(this, Guid.NewGuid().ToString(), new ElementId(material.Id));
//add the elementID:tracedata to the tags dictionary on the real protogeometry input
shapeReference.Tags.AddTag(this.InternalElementId.ToString(), traceData);
TransactionManager.Instance.TransactionTaskDone();
ElementBinder.SetRawDataForTrace(traceData);
}
#endregion
#region Helpers for private constructors
/// <summary>
/// Create a new DirectShape element from given list of Revit GeometryObjects, document, category, and Iddata
/// </summary>
private static Autodesk.Revit.DB.DirectShape NewDirectShape(
IList<Autodesk.Revit.DB.GeometryObject> geos,
Document doc,
ElementId categoryId,
string appGuid,
string shapeName)
{
var ds = Autodesk.Revit.DB.DirectShape.CreateElement(doc, categoryId);
ds.ApplicationId = appGuid;
ds.ApplicationDataId = Guid.NewGuid().ToString();
ds.SetShape(geos);
ds.Name = shapeName;
return ds;
}
private static IList<GeometryObject> GenerateTessellatedGeo(DesignScriptEntity shapeReference, ElementId materialId)
{
IList<GeometryObject> tessellatedShape = null;
if (shapeReference is Autodesk.DesignScript.Geometry.Mesh)
{
tessellatedShape = (shapeReference as Autodesk.DesignScript.Geometry.Mesh).ToRevitType(
TessellatedShapeBuilderTarget.Mesh,
TessellatedShapeBuilderFallback.Salvage,
MaterialId: materialId);
}
else if (shapeReference is Autodesk.DesignScript.Geometry.Surface)
{
// Defer to tessellated shape if BRep shape for some reason fails
GeometryObject geometry = null;
try
{
geometry = DynamoToRevitBRep.ToRevitType(shapeReference as Autodesk.DesignScript.Geometry.Surface, true, materialId);
}
catch
{
}
if (geometry != null)
{
tessellatedShape = new List<GeometryObject>() { geometry };
}
else
{
tessellatedShape = (shapeReference as Autodesk.DesignScript.Geometry.Surface).ToRevitType(TessellatedShapeBuilderTarget.AnyGeometry, TessellatedShapeBuilderFallback.Mesh, MaterialId: materialId);
}
}
else if (shapeReference is Autodesk.DesignScript.Geometry.Solid)
{
// Defer to tessellated shape if BRep shape for some reason fails
GeometryObject geometry = null;
try
{
geometry = DynamoToRevitBRep.ToRevitType(shapeReference as Autodesk.DesignScript.Geometry.Solid, true, materialId);
}
catch
{
}
if (geometry != null)
{
tessellatedShape = new List<GeometryObject>() { geometry };
}
else
{
tessellatedShape = (shapeReference as Autodesk.DesignScript.Geometry.Solid).ToRevitType(TessellatedShapeBuilderTarget.AnyGeometry, TessellatedShapeBuilderFallback.Mesh, MaterialId: materialId);
}
}
if (tessellatedShape == null)
{
throw new ArgumentException(Revit.Properties.Resources.DirectShapeInvalidArgument);
}
return tessellatedShape;
}
#endregion
#region Private mutators
/// <summary>
/// SetInternalElement to a DirectShape element
/// </summary>
private void InternalSetDirectShape(Autodesk.Revit.DB.DirectShape shape)
{
this.InternalDirectShape = shape;
this.InternalElementId = shape.Id;
this.InternalUniqueId = shape.UniqueId;
}
/// <summary>
/// Sets the internalDirectShape's shape to point to some geometry,
/// this method also generates tessellated geometry from the protogeometry object
/// and sets the material of the generated Revit faces
/// </summary>
private void InternalSetShape(DesignScriptEntity shapeReference, ElementId materialId, string currentSyncId)
{
//if the elementID for the current directShape revitElement exists on the input Geometry AND
//the value stored at that key is equal to the materialId we're trying to set AND
//the previousState's syncId (in the tags dictionary) equals the current syncId (from trace)
//then we do not need to regenerate
//first lookup the state on the input geometry
var previousState = shapeReference.Tags.LookupTag(this.InternalElementId.ToString()) as DirectShapeState;
//then compare values
if (previousState != null && previousState.materialId == materialId.Value && previousState.syncId == currentSyncId)
{
return;
}
TransactionManager.Instance.EnsureInTransaction(Document);
var tessellatedShape = GenerateTessellatedGeo(shapeReference, materialId);
this.InternalDirectShape.SetShape(tessellatedShape);
//update the value in trace, since we had to modify the geometry we need a new syncId
var updatedTraceData = new DirectShapeState(this, Guid.NewGuid().ToString(), materialId);
ElementBinder.SetRawDataForTrace(updatedTraceData);
//place new values in the tags dict
if (shapeReference.Tags.LookupTag(this.InternalElementId.ToString()) == null)
{
shapeReference.Tags.AddTag(this.InternalElementId.ToString(), updatedTraceData);
}
else
{
var storedState = shapeReference.Tags.LookupTag(this.InternalElementId.ToString()) as DirectShapeState;
storedState.syncId = updatedTraceData.syncId;
storedState.materialId = updatedTraceData.materialId;
storedState.IntID = updatedTraceData.IntID;
storedState.StringID = updatedTraceData.StringID;
}
TransactionManager.Instance.TransactionTaskDone();
}
/// <summary>
/// Sets the internalDirectShape to have a new name
/// if this method detects the default string it generates a more specific name
/// </summary>
private void InternalSetName(DesignScriptEntity shapeReference, string name, Material material, Category category)
{
if (name == DEFAULT_NAME)
{
name = string.Format("DirectShape" + "(Geometry = {0}, Category = {1}, Material ={2}.)",
shapeReference.ToString(),
category != null ? category.Name : "",
material != null ? material.Name : "");
}
if (name != this.InternalDirectShape.Name)
{
TransactionManager.Instance.EnsureInTransaction(Document);
this.InternalDirectShape.SetName(name);
TransactionManager.Instance.TransactionTaskDone();
}
}
#endregion
#region Public static constructors
/// <summary>
/// Create a Revit DirectShape given some geometry, a name for the shape, a Category, and Material.
/// The geometry will be tessellated before being placed in the Revit model
/// The category of a DirectShape cannot be changed after creation, so
/// a new DirectShape will be generated if the category input is changed.
/// </summary>
/// <param name="geometry">A Solid or Surface that will be tessellated and placed in the Revit model as a DirectShape</param>
/// <param name="name">A string name for the DirectShape</param>
/// <param name="category">Must be a top level Built-in Category</param>
/// <param name="material">A Material to apply to the faces of the DirectShape</param>
/// <returns>A DirectShape Element</returns>
public static DirectShape ByGeometry(Autodesk.DesignScript.Geometry.Geometry geometry,
Category category,
[DefaultArgumentAttribute(" DirectShape.DynamoPreviewMaterial")]Material material,
string name = DEFAULT_NAME)
{
if (geometry == null)
{
throw new ArgumentNullException("geometry");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (category == null)
{
throw new ArgumentNullException("category");
}
if (material == null)
{
throw new ArgumentNullException("material");
}
if (geometry is Autodesk.DesignScript.Geometry.Solid || geometry is Autodesk.DesignScript.Geometry.Surface)
{
return new DirectShape(geometry, name, category, material);
}
throw new ArgumentException(Revit.Properties.Resources.DirectShapeInvalidArgument);
}
/// <summary>
/// Create a Revit DirectShape given some geometry, a name for the shape, a Category, and Material.
/// The geometry will be tessellated before being placed in the Revit model
/// The category of a DirectShape cannot be changed after creation, so
/// a new DirectShape will be generated if the category input is changed.
/// </summary>
/// <param name="mesh">A Mesh that will be tessellated and placed in the Revit model as a DirectShape</param>
/// <param name="name">A string name for the DirectShape</param>
/// <param name="category">Must be a top level Built-in Category</param>
/// <param name="material">A Material to apply to the faces of the DirectShape</param>
/// <returns>A DirectShape Element</returns>
public static DirectShape ByMesh(Autodesk.DesignScript.Geometry.Mesh mesh,
Category category,
[DefaultArgumentAttribute(" DirectShape.DynamoPreviewMaterial")]Material material,
string name = DEFAULT_NAME)
{
if (mesh == null)
{
throw new ArgumentNullException("mesh");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (category == null)
{
throw new ArgumentNullException("category");
}
if (material == null)
{
throw new ArgumentNullException("material");
}
return new DirectShape(mesh, name, category, material);
}
#endregion
#region static constructors
/// <summary>
/// Construct a DirectShape from the Revit document.
/// </summary>
/// <param name="directShape"></param>
/// <param name="isRevitOwned"></param>
/// <returns></returns>
internal static DirectShape FromExisting(Autodesk.Revit.DB.DirectShape directShape, bool isRevitOwned)
{
return new DirectShape(directShape)
{
IsRevitOwned = isRevitOwned
};
}
static DirectShape()
{
DynamoPreviewMaterial = Material.ByName(Document.GetElement(MaterialsManager.Instance.DynamoMaterialId).Name);
DYNAMO_DIRECTSHAPE_APP_GUID = Guid.Parse("03deaabe-6989-4d20-ba68-557001d2f45c");
}
#endregion
/// <summary>
/// Please see InternalSetName method
/// </summary>
public override string ToString()
{
return InternalDirectShape.IsValidObject ? InternalDirectShape.Name : String.Empty;
}
}
}