GithubHelp home page GithubHelp logo

mcneel / rhino-developer-samples Goto Github PK

View Code? Open in Web Editor NEW
606.0 81.0 330.0 195.79 MB

Rhino and Grasshopper developer sample code

Home Page: http://developer.rhino3d.com

License: Other

C# 39.14% Python 7.41% C++ 38.08% HTML 1.53% C 3.43% GLSL 0.15% Visual Basic .NET 7.09% VBScript 0.19% JavaScript 2.95% CSS 0.02%
rhino grasshopper sdk samples

rhino-developer-samples's Introduction

Rhino Developer Samples

This repository contains all the sample developer code for programming in the Rhino and Grasshopper ecosystem.

The source of this repository will be used to populate the Samples section of the Rhino Developer website.

Much like the Rhino Developer website, the version of Rhino that these samples are compatible with are determined by which branch of this repository one is viewing:

  • The master branch corresponds to the version of Rhino currently in active development (the WIP branch).
  • The 7 branch correspondes to Rhino 7, the 6 branch corresponds to Rhino 6, etc.
  • Older versions of Rhino will be archived into version-specific branches (for example: 5).

Samples by SDK or Language

The samples in this repository are organized by folders that correspond to the different SDKs that make up the Rhino development platform. For more information about the different Rhino SDKs and supported languages, please see the Rhino Developer website. This repository contains samples for:

Building Samples

TODO: More info about building coming soon.

Why are the sample projects prefixed with the word Sample?

We gave each sample project a unique name in order to avoid command name collisions when these samples are run in Rhino. The word Sample is prefixed to distinguish it from developer "Test" commands that sometimes used to test out new functionality in Rhino. Since it is possible - and probable - that samples might be built, run, and tested in multiple languages, so we opted for a language code (C/C++ samples omit this simply because they came first), before the name of the sample.

Testing

TODO: More info coming soon

rhino-developer-samples's People

Contributors

acormier avatar andresjacobo avatar andylebihan avatar croudyj avatar dalefugier avatar dan-rigdon-bel avatar davidrutten avatar deranen avatar fraguada avatar golsby avatar jesterking avatar johnmorse avatar jussiaaltonen avatar matulski avatar pearswj avatar piac avatar sbaer avatar scotttd avatar sodermax avatar travisserio avatar uozcan12 avatar zooid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rhino-developer-samples's Issues

Unable to use delete and enter keys

_rhinoCore = new Rhino.Runtime.InProcess.RhinoCore( Rhino.Runtime.InProcess.WindowStyle.Maximized);

The Rhino program opened using this code cannot use the Delete and Enter keys, but can be used by opening Rhino separately. But typing the command 'delete' can be used

C++ export and import data

I am writing a utility to operate on rhino files so I can export the mesh data.
Is that supported on your api ? Not sure if you provide file level api you see ..

Next I want to write a plug-in to pull and push data via the rhino program itself. The idea is to update the mesh as the architect works. I assume that I need some sort of developer account to allow my colleagues to use that ?

How to add command for SampleMeshExport

I am a beginer of Rhino developer and have successfully complied the SampleExportMesh. I want to known how to add a command to call the function to export a mesh to a file?

SampleViewportRenderer doesn't work in Rhino 6

Hi,

I originally came across this issue in our own CRhinoDisplayPipeline implementation however I encounter the same thing in the SampleViewportRenderer in this repo.

In short, it doesn't work. When you activate the renderer nothing ever gets displayed in the viewport. It just keeps displaying whatever was there previously and if you navigate the display remains unchanged.

I can fix this by providing a derived implementation of the EngineClass() virtual method. EG:

const ON_ClassId* CSampleDisplayPipeline::EngineClass()
{
	return &CRhinoDisplayEngine_OGL::m_CRhinoDisplayEngine_OGL_class_rtti;
}

On my machine I then get the viewport renders.

If I change the EngineClass() implementation to just return CRhinoDisplayPipeline::EngineClass() then things stop working again. In fact, the EngineClass() method gets called about 15 times. When it returns the OGL engine class it only gets called once.

Unfortunately, even though with these fixes it works on my desktop development machine it does not work on the laptop we tested. The ShowFrameBuffer method gets called however the viewport never gets updated. The only real difference we can think of between the two machines is that the laptop has an integrated and dedicated GPU (Rhino is running on the dedicated) while the development machine is just a dedicated GPU. So far we've only tested one desktop and one laptop but will be trying another laptop tomorrow. However, I can't think why there should be any issue given that ShowFrameBuffer is working at the MFC/WindowsSDK level.

Note that the Rhino 5 version of the plugins (both sample and our one) works fine in all cases. It's only for Rhino 6 that we've needed to override EngineClass() and are encountering the laptop issue.

why not must setPath librayPath?

When I am using 3dmLoader, why do I have to set the librarypath? Can this step be omitted?

just,like-this:

loader = new Rhino3dmLoader();
// loader.setLibraryPath( 'https://cdn.jsdelivr.net/npm/[email protected]/' );
loader.load( 'http://127.0.0.1:5502/shoe/shoe.3dm', function ( object ) {
debugger
console.log(object);1
scene.add( object );
render()
}, (e) => {
		console.log(e)
}, (e) => {
		console.log(e)
})

not

// open 
loader.setLibraryPath( 'https://cdn.jsdelivr.net/npm/[email protected]/' );

help !

ResetBlock.rvb throws 'undefined variable' error

The script ResetBlock.rvb throws an 'undefined variable: arrXform' error.
This can be fixed by adding arrXform to the Dim declarations on line 17, since the script uses Option Explicit:
Dim arrBlocks, strBlock, arrPoint, arrVector, arrXform

rhino.inside/dotnet/SampleUnitTests does not work

I have cloned rhino developer samples inside visual studio 2019 (16.11.3) starting from the opening dialog to clone a project.
Then opened the Rhino.Inside SampleUnitTests & built it, without making any changes (even though the readme.txt suggests to make changes, all these were already done or set correctly).

When I use the Visual Studio built-in unit test running facilities, I first get an error that Grasshopper.dll is not found. I see that all the NuGet packages (rhino.inside, rhinowindows, grasshopper, rhinocommon) are installed in the %USER%.nuget\packages directory, but the dependent DLL's are not copied over to the directory where the unit test runner can find them. So, I copied over all dependent DLLs from nuget packages into the build output directory. Then I get a different error (see below), and I am stuck trying to solve this.

I was hoping to just clone, build and run the unit tests project without any hassle.

System.DllNotFoundException
Unable to load DLL 'RhinoLibrary': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at Rhino.Runtime.InProcess.RhinoCore.InternalStartup(Int32 argc, String[] argv, StartupInfo& info, IntPtr hostWnd)
   at Rhino.Runtime.InProcess.RhinoCore..ctor(String[] args, WindowStyle windowStyle, IntPtr hostWnd)
   at Rhino.Test.GrasshopperSingleton.InitializeCore() in D:\zandbak\rhino-developer-samples\rhino.inside\dotnet\SampleUnitTests\GrasshopperTests\GrasshopperFixture.cs:line 148
   at Rhino.Test.GrasshopperSingleton..ctor() in D:\zandbak\rhino-developer-samples\rhino.inside\dotnet\SampleUnitTests\GrasshopperTests\GrasshopperFixture.cs:line 117
   at Rhino.Test.GrasshopperSingleton.get_Instance() in D:\zandbak\rhino-developer-samples\rhino.inside\dotnet\SampleUnitTests\GrasshopperTests\GrasshopperFixture.cs:line 90
   at Rhino.Test.GHFileFixture..ctor(String filePath) in D:\zandbak\rhino-developer-samples\rhino.inside\dotnet\SampleUnitTests\GrasshopperTests\GrasshopperFixture.cs:line 24
   at SampleGHTests.PrimitivesFixture..ctor() in D:\zandbak\rhino-developer-samples\rhino.inside\dotnet\SampleUnitTests\GrasshopperTests\TestPrimitives.cs:line 17

Unable to load RhinoLibrary dll while running HelloWorld sample

Hello ! I tried to run the hello world example in C# but I get an error at this line using (new RhinoCore(args)) :
System.DllNotFoundException : 'unable to load 'RhinoLibrary' DLL: The specified module cannot be found. (HRESULT exception : 0x8007007E)'

I re-referenced RhinoCommon and Rhino.Inside from the NuGet packages just to be sure. But I still get the issue...

Am I missing a setting step?

Cannot run RhinoInside+Grasshopper Samples, any configuration

Hello, i am not sure if this is the correct Repo for posting my issue, but:

i have trouble running Headless Rhino/RhinoInside with Grasshopper-Plugin.

I get the following Exception, when using net481:
InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'Grasshopper.Plugin.GH_RhinoScriptInterface'.

When using dotnetcore 7, i can't even load the correct DLLs or receive an "Error: HResult E_Fail has been returned from a call to a COM component", which i can't debug further.

Are there any restrictions on using specific versions?

My setup is:

  • current Visual Studio 2022 Community Edition (17.10)
  • both dotnet 481 and dotnet core 7 (dotnet core 8 is also installed, but didn't try that)
  • both Rhino 7 and 8 are installed
  • nuget-packages: .NET481: RhinoCommon + Grasshopper 7.36.23346.16351 (with custom RhinoInside-Resolver as well as the nuget-package with version 7.0.0), ; dotnetcore7: RhinoCommon + Grasshopper 8.7.24138.15431 (with custom RhinoInside-Resolver)
  • both Rhino-Versions are licensed and can be opened
  • Grasshopper is installed as Plugin
  • GH-Script is added as embedded Resource
  • Tried with Resolver-Flag "UseLatest" set to either true or false.

Ideally, i can run Rhino 8 Headless with dotnetcore 7 to be "future-proof", but i hadn't any luck for now.
I would also be happy, if i can run any variant for starters, but no Rhino 7 Licenses can be bought anymore.

My Grasshopper-Scripts uses revit-internal api to generate a rvt based on a DXF-File.
Can somebody help me with that or provide suggestions? That would be awesome - any hint helps

Here is the code, which i used/changed:

Program.cs: (adapted part)
`
namespace RhinoGrassHopperRunner
{
class Program
{

      static Program()
      {
          RhinoInside.Resolver.Initialize();
          Console.WriteLine("Initializing RhinoInside.Resolver");
      }

      static void Main(string[] args)
      {
          using (var core = new Rhino.Runtime.InProcess.RhinoCore())
          {
              RunHelper();
          }
      }

      // Currently need a separate RunHelper function so the .NET runtime won't attempt to load the
      // Grasshopper assembly until after RhinoCore has been created. This should be "fixable" in a
      // future version of the RhinoInside nuget package
      static void RunHelper()
      {
       // Extract definition to sample location as executable
       var assembly = typeof(Program).Assembly;
       string dir = System.IO.Path.GetDirectoryName(assembly.Location);
       var scriptName = "DXF2RVT.gh";
       string filePath = System.IO.Path.Combine(dir, scriptName);
      
       using (var resStream = assembly.GetManifestResourceStream("RhinoGrassHopperRunner." + scriptName))
       using (var outStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
       {
           resStream.CopyTo(outStream);
       }
      var plugins = Rhino.PlugIns.PlugIn.GetInstalledPlugIns().OrderBy(x => x.Value);
      Console.WriteLine("plugins:", plugins.Select(x => x.Key + "  " + x.Value));
      // Start grasshopper in "headless" mode
      var plugin = plugins.FirstOrDefault(x => x.Value.Contains("Grasshopper")).Key;
      //if (string.IsNullOrEmpty(plugin))
      //{
      //    Console.WriteLine("Grasshopper not found");
      //    return;
      //}
      var pluginObject = Rhino.RhinoApp.GetPlugInObject(plugin);
      var type = pluginObject.GetType();
      var castedObject = (Grasshopper.Plugin.GH_RhinoScriptInterface)pluginObject;
      castedObject.RunHeadless();
      ....

`

Resolver.cs:

`
using System.Reflection;
using System.Runtime.InteropServices;

// Code from https://github.com/mcneel/compute.rhino3d/blob/8.x/src/compute.geometry/Resolver.cs
namespace RhinoInside
{
public class Resolver
{
///


/// Set up an assembly resolver to load RhinoCommon and other Rhino
/// assemblies from where Rhino is installed
///

public static void Initialize()
{
Console.WriteLine("Initializing RhinoInside.Resolver");
if (System.IntPtr.Size != 8)
throw new Exception("Only 64 bit applications can use RhinoInside");
AppDomain.CurrentDomain.AssemblyResolve += ResolveForRhinoAssemblies;
}

    static string _rhinoSystemDirectory;

    /// <summary>
    /// Directory used by assembly resolver to attempt load core Rhino assemblies. If not manually set,
    /// this will be determined by inspecting the registry
    /// 
    /// This is the C:/Program Files/Rhino 8/System directory on Windows
    /// This is the Rhinoceros.app/Contents/Frameworks directory on Mac
    /// </summary>
    public static string RhinoSystemDirectory
    {
        get
        {
            //return "C:\\Program Files\\Rhino 7\\System";
            // THIS USES THE RHINO 8 DIRECTORY
            if (string.IsNullOrWhiteSpace(_rhinoSystemDirectory))
                _rhinoSystemDirectory = FindRhinoSystemDirectory(); 
            return _rhinoSystemDirectory;
        }
        set
        {
            _rhinoSystemDirectory = value;
        }
    }

    /// <summary>
    /// Whether or not to use the newest installation of Rhino on the system. By default the resolver will only use an
    /// installation with a matching major version.
    /// </summary>
    public static bool UseLatest { get; set; } = true; // was true to use rhino8

    public static string AssemblyPathFromName(string systemDirectory, string name)
    {
        if (name == null || name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase))
            return null;

        // load Microsoft.macOS in the default context as xamarin initialization requires it there
        if (name == "Microsoft.macOS")
            return null;

        //if (name.Contains("Rhino") || name.Contains("Grasshopper"))
        //{
            name = name.Split(',')[0];
        //}
        if (name.Contains("Grasshopper"))
        {
            systemDirectory = "C:\\Program Files\\Rhino 7\\Plug-ins\\Grasshopper";
        }
        else if(name.Contains("Rhino") && systemDirectory == null)
        {
            systemDirectory = "C:\\Program Files\\Rhino 7\\System";
        }
        string path = null;
        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            path = Path.Combine(systemDirectory, "RhCore.framework/Resources", name + ".dll");
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            //path = Path.Combine(systemDirectory, "netcore", name + ".dll");
            if (!File.Exists(path))
            {
               path = Path.Combine(systemDirectory, name + ".dll");
            }
            if (!File.Exists(path))
            {
                var intPath = typeof(int).Assembly.Location;
                string directory = System.IO.Path.GetDirectoryName(intPath);
                path = Path.Combine(directory, name + ".dll");
                if (!File.Exists(path) || name.Contains(".Drawing") || name.Contains("WindowsBase"))
                {
                    int index = directory.IndexOf("NETCORE", StringComparison.OrdinalIgnoreCase);
                    directory = directory.Substring(0, index) + "WindowsDesktop" + directory.Substring(index + "NETCORE".Length);
                    path = Path.Combine(directory, name + ".dll");
                }
            }
        }
        return path;
    }

    static Assembly ResolveForRhinoAssemblies(object sender, ResolveEventArgs args)
    {
        string path = AssemblyPathFromName(RhinoSystemDirectory, args.Name);
        //// remove everything after first occurrence of ,
        //var cleanedName = path.Split(',');

        //path = cleanedName[0] + ".dll";

        if (File.Exists(path))
            return Assembly.LoadFrom(path);
        return null;
    }

    static string FindRhinoSystemDirectory()
    {
        var major = Assembly.GetExecutingAssembly().GetName().Version.Major;

        if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
        {
            string baseName = @"SOFTWARE\McNeel\Rhinoceros";
            using var baseKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(baseName);
            string[] children = baseKey.GetSubKeyNames();
            Array.Sort(children);
            string versionName = "";
            for (int i = children.Length - 1; i >= 0; i--)
            {
                // 20 Jan 2020 S. Baer (https://github.com/mcneel/rhino.inside/issues/248)
                // A generic double.TryParse is failing when run under certain locales.
                if (double.TryParse(children[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
                {
                    if (d < 8.0)
                        continue;

                    versionName = children[i];

                    if (!UseLatest && (int)Math.Floor(d) != major)
                        continue;

                    using var installKey = baseKey.OpenSubKey($"{versionName}\\Install");
                    string corePath = installKey.GetValue("CoreDllPath") as string;
                    if (System.IO.File.Exists(corePath))
                    {
                        return System.IO.Path.GetDirectoryName(corePath);
                    }
                }
            }
        }

        return null;
    }
}

}
`
.csproj:
image

I also tried posting my issue in galer7/run-grasshopper-demo#1 , but the owner-repo also said that the examples are broken since the rhino 8 update, as seen in his reply.

Is there any way possible to achieve running RhinoInside / Grasshopper to perform these Revit-Transformations?
Any pointers or help is much appreciated.

Thank you very much!!
BR, Edvin

rhino.inside/dotnet/SampleRunGrasshopper is still working?

Hi @fraguada,

I am not able to make work your sample project:

https://github.com/mcneel/rhino-developer-samples/blob/7/rhino.inside/dotnet/SampleRunGrasshopper/Program.cs

I have the nuget libraries and using .NET 4.8.
image

But when I run I got:
System.MissingMethodException: 'Method not found: 'Void Grasshopper.Plugin.GH_RhinoScriptInterface.RunHeadless()'.'
at


For some reason looks like is referencing other Grasshopper.dll version, so I tried subscribing to AppDomain.CurrentDomain.AssemblyResolve to load the Grasshopper.dll from the Rhino 7 Plug-ins folder, but after that in the same code line I got System.NullReferenceException: 'Object reference not set to an instance of an object.'.

Could you or someone look into this please?

Thanks.

Converting OBJ to 3DM: Validity Issues in Generated Files

I’m attempting to load and convert an OBJ file to 3DM format using the rhino3dm library. Here’s the relevant code snippet:

import rhino3dm from 'rhino3dm';
import * as fs from 'fs';
import * as THREE from 'three';
import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';

const rhino = await rhino3dm();
console.log('Loaded rhino3dm.');

const fileContent = fs.readFileSync('public/models/test.obj').toString();

const loader = new OBJLoader();
const obj = loader.parse(fileContent);

let exportGeometry = null;
if (obj.children) {
    obj.children.forEach((mesh) => {
        if (!exportGeometry) {
            console.log('here');
            exportGeometry = mesh.geometry;
        } else {
            exportGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries([exportGeometry, mesh.geometry], false);
        }
    });
}
const rhinoMesh = rhino.Mesh.createFromThreejsJSON({data: exportGeometry})

const doc = new rhino.File3dm()
doc.objects().add(rhinoMesh, null)

let opts = new rhino.File3dmWriteOptions()
opts.version = 6;
let buffer = doc.toByteArrayOptions(opts);
fs.writeFileSync('public/models/test.3dm', buffer);
console.log('3DM file saved successfully.');

The code successfully generates a 3DM file, but unfortunately, the resulting file is not valid. When re-uploaded to a 3D viewer, it fails to load properly. I’ve followed the example from the repository, but I’m encountering this issue.

Any insights on why the generated 3DM file isn’t valid, and how I can address this problem?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.