using System;
using System.Collections.Generic;
using System.IO;
using Rhino;
using Rhino.Commands;
using Rhino.DocObjects;
using Rhino.Geometry;
namespace BlockTest
{
public class BlockTest : Command
{
static BlockTest _instance;
public BlockTest()
{
_instance = this;
}
///The only instance of the BlockTest command.
public static BlockTest Instance
{
get { return _instance; }
}
public override string EnglishName
{
get { return "BlockTestCommand"; }
}
protected override Result RunCommand(RhinoDoc doc, RunMode mode)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonDocuments) + "\\BlockTest\\D\\D.3dm";
InsertLinkedBlock(path, doc, InstanceDefinitionUpdateType.LinkedAndEmbedded);
return Result.Success;
}
///
/// Creates linked block definition of given path at World Origin
///
/// Path of the file to be linked
/// Document in which the file is to be linked
/// Embedded, linked and embedded or linked
/// If successful, returns the index of the newly created linked block
public static int InsertLinkedBlock(string filePath, RhinoDoc doc, InstanceDefinitionUpdateType updateType, string blockName = null)
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Cannot find the specified file");
}
string extension = Path.GetExtension(filePath);
if (extension != ".3dm" || extension == ".stp")
{
throw new InvalidOperationException("Wrong type of file used");
}
if (blockName == null)
{
blockName = Path.GetFileNameWithoutExtension(filePath);
}
InstanceDefinition existingBlock = doc.InstanceDefinitions.Find(blockName);
if (existingBlock != null)
return existingBlock.Index;
//Initially adding a dummy geometrybase
List tempInitialObjects = new List() { new Point(Plane.WorldXY.Origin) };
List tempInitialAttributes = new List() { new ObjectAttributes() };
int indexOfAddedBlock = doc.InstanceDefinitions.Add(blockName, "", Plane.WorldXY.Origin, tempInitialObjects, tempInitialAttributes);
bool modified = doc.InstanceDefinitions.ModifySourceArchive(indexOfAddedBlock, Rhino.FileIO.FileReference.CreateFromFullPath(filePath), updateType, true);
if (!modified)
{
doc.InstanceDefinitions.Delete(indexOfAddedBlock, true, true);
return -1;
}
return indexOfAddedBlock;
}
}
}