public static GrasshopperDefinition FromUrl(string url, bool cache)
        {
            GrasshopperDefinition rc = DataCache.GetCachedDefinition(url);

            if (rc != null)
            {
                Console.WriteLine("Using cached definition");
                return(rc);
            }

            var archive = ArchiveFromUrl(url);

            if (archive == null)
            {
                return(null);
            }

            rc = Construct(archive);
            if (cache)
            {
                DataCache.SetCachedDefinition(url, rc);
                rc.InDataCache = true;
            }
            return(rc);
        }
Exemple #2
0
        static Response GetIoNames(NancyContext ctx)
        {
            string body = ctx.Request.Body.AsString();

            if (body.StartsWith("[") && body.EndsWith("]"))
            {
                body = body.Substring(1, body.Length - 2);
            }

            Schema input = JsonConvert.DeserializeObject <Schema>(body);

            // load grasshopper file
            GrasshopperDefinition definition = GrasshopperDefinition.FromUrl(input.Pointer, true);

            if (definition == null)
            {
                definition = GrasshopperDefinition.FromBase64String(input.Algo);
            }
            if (definition == null)
            {
                throw new Exception("Unable to load grasshopper definition");
            }

            string jsonResponse = JsonConvert.SerializeObject(definition.GetInputsAndOutputs());

            Response res = jsonResponse;

            res.ContentType = "application/json";
            return(res);
        }
        public static void SetCachedDefinition(string key, GrasshopperDefinition definition, string data)
        {
            CachedDefinition cachedef = new CachedDefinition
            {
                Definition = definition,
                WatchedFileRuntimeSerialNumber = GrasshopperDefinition.WatchedFileRuntimeSerialNumber
            };

            System.Runtime.Caching.MemoryCache.Default.Set(key, cachedef, CachePolicy);

            if (!string.IsNullOrWhiteSpace(data))
            {
                string filename = DefinitionCacheFileName(key);
                if (filename != null && !System.IO.File.Exists(filename))
                {
                    try
                    {
                        if (!System.IO.Directory.Exists(DefinitionCacheDirectory))
                        {
                            System.IO.Directory.CreateDirectory(DefinitionCacheDirectory);
                        }

                        System.IO.File.WriteAllText(filename, data);
                        System.Threading.Tasks.Task.Run(() => DataCache.CGCacheDirectory());
                    }
                    catch (Exception ex)
                    {
                        Serilog.Log.Error($"Unable to write cache file: {filename}");
                        Serilog.Log.Error(ex, "File error exception");
                    }
                }
            }
        }
Exemple #4
0
        public static GrasshopperDefinition FromUrl(string url, bool cache)
        {
            GrasshopperDefinition rc = DataCache.GetCachedDefinition(url);

            if (rc != null)
            {
                LogDebug("Using cached definition");
                return(rc);
            }

            if (Guid.TryParse(url, out Guid componentId))
            {
                rc = Construct(componentId);
            }
            else
            {
                var archive = ArchiveFromUrl(url);
                if (archive == null)
                {
                    return(null);
                }

                rc = Construct(archive);
                rc.IsLocalFileDefinition = !url.StartsWith("http", StringComparison.OrdinalIgnoreCase) && File.Exists(url);
            }
            if (cache)
            {
                DataCache.SetCachedDefinition(url, rc);
                rc.InDataCache = true;
            }
            return(rc);
        }
Exemple #5
0
        private static GrasshopperDefinition Construct(Guid componentId)
        {
            var component = Grasshopper.Instances.ComponentServer.EmitObject(componentId) as GH_Component;

            if (component == null)
            {
                return(null);
            }

            var definition = new GH_Document();

            definition.AddObject(component, false);

            // raise DocumentServer.DocumentAdded event (used by some plug-ins)
            Grasshopper.Instances.DocumentServer.AddDocument(definition);

            GrasshopperDefinition rc = new GrasshopperDefinition(definition);

            rc._singularComponent = component;
            foreach (var input in component.Params.Input)
            {
                rc._input[input.NickName] = new InputGroup(input);
            }
            foreach (var output in component.Params.Output)
            {
                rc._output[output.NickName] = output;
            }
            return(rc);
        }
Exemple #6
0
        public static void SetCachedDefinition(string key, GrasshopperDefinition definition)
        {
            CachedDefinition cachedef = new CachedDefinition
            {
                Definition = definition,
                WatchedFileRuntimeSerialNumber = GrasshopperDefinition.WatchedFileRuntimeSerialNumber
            };

            System.Runtime.Caching.MemoryCache.Default.Set(key, cachedef, CachePolicy);
        }
Exemple #7
0
        private static GrasshopperDefinition Construct(GH_Archive archive)
        {
            var definition = new GH_Document();

            if (!archive.ExtractObject(definition, "Definition"))
            {
                throw new Exception("Unable to extract definition from archive");
            }

            // raise DocumentServer.DocumentAdded event (used by some plug-ins)
            Grasshopper.Instances.DocumentServer.AddDocument(definition);

            GrasshopperDefinition rc = new GrasshopperDefinition(definition);

            foreach (var obj in definition.Objects)
            {
                IGH_ContextualParameter contextualParam = obj as IGH_ContextualParameter;
                if (contextualParam != null)
                {
                    IGH_Param param = obj as IGH_Param;
                    if (param != null)
                    {
                        rc._input[param.NickName] = new InputGroup(param);
                    }
                    continue;
                }

                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                string nickname     = group.NickName;
                var    groupObjects = group.Objects();
                if (nickname.Contains("RH_IN") && groupObjects.Count > 0)
                {
                    var param = groupObjects[0] as IGH_Param;
                    if (param != null)
                    {
                        rc._input[nickname] = new InputGroup(param);
                    }
                }

                if (nickname.Contains("RH_OUT") && groupObjects.Count > 0)
                {
                    var param = groupObjects[0] as IGH_Param;
                    if (param != null)
                    {
                        rc._output[nickname] = param;
                    }
                }
            }
            return(rc);
        }
        public static GrasshopperDefinition FromUrl(string url, bool cache)
        {
            var archive = ArchiveFromUrl(url);

            if (archive == null)
            {
                return(null);
            }

            GrasshopperDefinition rc = Construct(archive);

            return(rc);
        }
        Response GetIoNames(NancyContext ctx, bool asPost)
        {
            GrasshopperDefinition definition;

            if (asPost)
            {
                string body = ctx.Request.Body.AsString();
                if (body.StartsWith("[") && body.EndsWith("]"))
                {
                    body = body.Substring(1, body.Length - 2);
                }

                Schema input = JsonConvert.DeserializeObject <Schema>(body);
                lock (_ghsolvelock)
                {
                    // load grasshopper file
                    definition = GrasshopperDefinition.FromUrl(input.Pointer, true);
                    if (definition == null)
                    {
                        definition = GrasshopperDefinition.FromBase64String(input.Algo, true);
                    }
                }
            }
            else
            {
                string url = Request.Query["Pointer"].ToString();
                lock (_ghsolvelock)
                {
                    definition = GrasshopperDefinition.FromUrl(url, true);
                }
            }

            if (definition == null)
            {
                throw new Exception("Unable to load grasshopper definition");
            }

            var responseSchema = definition.GetInputsAndOutputs();

            responseSchema.CacheKey = definition.CacheKey;
            responseSchema.Icon     = definition.GetIconAsString();
            string jsonResponse = JsonConvert.SerializeObject(responseSchema);

            Response res = jsonResponse;

            res.ContentType = "application/json";
            return(res);
        }
Exemple #10
0
        public static void SetCachedSolveResults(string key, string jsonResults, GrasshopperDefinition definition)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return;
            }

            var cache = new CachedResults
            {
                Definition = definition,
                WatchedFileRuntimeSerialNumber = GrasshopperDefinition.WatchedFileRuntimeSerialNumber,
                Json = jsonResults
            };

            System.Runtime.Caching.MemoryCache.Default.Add(key, cache, CachePolicy);
        }
Exemple #11
0
        static Response GrasshopperSolveHelper(Schema input, string body, System.Diagnostics.Stopwatch stopwatch)
        {
            // load grasshopper file
            GrasshopperDefinition definition = GrasshopperDefinition.FromUrl(input.Pointer, true);

            if (definition == null && !string.IsNullOrWhiteSpace(input.Algo))
            {
                definition = GrasshopperDefinition.FromBase64String(input.Algo, true);
            }
            if (definition == null)
            {
                throw new Exception("Unable to load grasshopper definition");
            }

            int recursionLevel = input.RecursionLevel + 1;

            definition.Definition.DefineConstant("ComputeRecursionLevel", new Grasshopper.Kernel.Expressions.GH_Variant(recursionLevel));

            definition.SetInputs(input.Values);
            long decodeTime = stopwatch.ElapsedMilliseconds;

            stopwatch.Restart();
            var output = definition.Solve();

            output.Pointer = definition.CacheKey;
            long solveTime = stopwatch.ElapsedMilliseconds;

            stopwatch.Restart();
            string   returnJson = JsonConvert.SerializeObject(output, GeometryResolver.Settings);
            long     encodeTime = stopwatch.ElapsedMilliseconds;
            Response res        = returnJson;

            res.ContentType = "application/json";
            res             = res.WithHeader("Server-Timing", $"decode;dur={decodeTime}, solve;dur={solveTime}, encode;dur={encodeTime}");
            if (definition.HasErrors)
            {
                res.StatusCode = Nancy.HttpStatusCode.InternalServerError;
            }
            else
            {
                if (input.CacheSolve)
                {
                    DataCache.SetCachedSolveResults(body, returnJson, definition);
                }
            }
            return(res);
        }
Exemple #12
0
        static Response Grasshopper(NancyContext ctx)
        {
            var    stopwatch = System.Diagnostics.Stopwatch.StartNew();
            string body      = ctx.Request.Body.AsString();

            if (body.StartsWith("[") && body.EndsWith("]"))
            {
                body = body.Substring(1, body.Length - 2);
            }
            Schema input = JsonConvert.DeserializeObject <Schema>(body);

            // load grasshopper file
            GrasshopperDefinition definition = GrasshopperDefinition.FromUrl(input.Pointer, true);

            if (definition == null)
            {
                definition = GrasshopperDefinition.FromBase64String(input.Algo);
            }
            if (definition == null)
            {
                throw new Exception("Unable to load grasshopper definition");
            }

            definition.SetInputs(input.Values);
            long decodeTime = stopwatch.ElapsedMilliseconds;

            stopwatch.Restart();
            var  output    = definition.Solve();
            long solveTime = stopwatch.ElapsedMilliseconds;

            stopwatch.Restart();
            string   returnJson = JsonConvert.SerializeObject(output, GeometryResolver.Settings);
            long     encodeTime = stopwatch.ElapsedMilliseconds;
            Response res        = returnJson;

            res.ContentType = "application/json";
            res             = res.WithHeader("Server-Timing", $"decode;dur={decodeTime}, solve;dur={solveTime}, encode;dur={encodeTime}");
            if (definition.HasErrors)
            {
                res.StatusCode = Nancy.HttpStatusCode.InternalServerError;
            }
            return(res);
        }
        private static GrasshopperDefinition Construct(GH_Archive archive)
        {
            var definition = new GH_Document();

            if (!archive.ExtractObject(definition, "Definition"))
            {
                throw new Exception("Unable to extract definition from archive");
            }

            GrasshopperDefinition rc = new GrasshopperDefinition(definition);

            foreach (var obj in definition.Objects)
            {
                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                string nickname     = group.NickName;
                var    groupObjects = group.Objects();
                if (nickname.Contains("RH_IN") && groupObjects.Count > 0)
                {
                    var param = groupObjects[0] as IGH_Param;
                    if (param != null)
                    {
                        rc._input[nickname] = new InputGroup(param);
                    }
                }

                if (nickname.Contains("RH_OUT") && groupObjects.Count > 0)
                {
                    var param = groupObjects[0] as IGH_Param;
                    if (param != null)
                    {
                        rc._output[nickname] = param;
                    }
                }
            }
            return(rc);
        }
        public static GrasshopperDefinition GetCachedDefinition(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return(null);
            }
            var def = System.Runtime.Caching.MemoryCache.Default.Get(key) as CachedDefinition;

            if (def == null)
            {
                string filename = DefinitionCacheFileName(key);
                if (filename != null && System.IO.File.Exists(filename))
                {
                    try
                    {
                        string data = System.IO.File.ReadAllText(filename);
                        return(GrasshopperDefinition.FromBase64String(data, true));
                    }
                    catch (Exception ex)
                    {
                        Serilog.Log.Error($"Unable to read cache file: {filename}");
                        Serilog.Log.Error(ex, "File error exception");
                    }
                }
                return(null);
            }
            if (def.Definition.IsLocalFileDefinition)
            {
                if (def.WatchedFileRuntimeSerialNumber != GrasshopperDefinition.WatchedFileRuntimeSerialNumber)
                {
                    System.Runtime.Caching.MemoryCache.Default.Remove(key);
                    return(null);
                }
            }
            return(def.Definition);
        }
Exemple #15
0
        static Response Grasshopper(NancyContext ctx)
        {
            var    stopwatch = System.Diagnostics.Stopwatch.StartNew();
            string body      = ctx.Request.Body.AsString();

            if (body.StartsWith("[") && body.EndsWith("]"))
            {
                body = body.Substring(1, body.Length - 2);
            }
            Schema input = JsonConvert.DeserializeObject <Schema>(body);

            if (input.CacheSolve)
            {
                // look in the cache to see if this has already been solved
                string cachedReturnJson = DataCache.GetCachedSolveResults(body);
                if (!string.IsNullOrWhiteSpace(cachedReturnJson))
                {
                    Response cachedResponse = cachedReturnJson;
                    cachedResponse.ContentType = "application/json";
                    return(cachedResponse);
                }
            }

            // 5 Feb 2021 S. Baer
            // Throw a lock around the entire solve process for now. I can easily
            // repeat multi-threaded issues by creating a catenary component with Hops
            // that has one point for A and multiple points for B.
            // We can narrow down this lock over time. As it stands, launching many
            // compute instances on one computer is going to be a better solution anyway
            // to deal with solving many times simultaniously.
            lock (_ghsolvelock)
            {
                // load grasshopper file
                GrasshopperDefinition definition = GrasshopperDefinition.FromUrl(input.Pointer, true);
                if (definition == null)
                {
                    definition = GrasshopperDefinition.FromBase64String(input.Algo, true);
                }
                if (definition == null)
                {
                    throw new Exception("Unable to load grasshopper definition");
                }

                definition.SetInputs(input.Values);
                long decodeTime = stopwatch.ElapsedMilliseconds;
                stopwatch.Restart();
                var output = definition.Solve();
                output.Pointer = definition.CacheKey;
                long solveTime = stopwatch.ElapsedMilliseconds;
                stopwatch.Restart();
                string   returnJson = JsonConvert.SerializeObject(output, GeometryResolver.Settings);
                long     encodeTime = stopwatch.ElapsedMilliseconds;
                Response res        = returnJson;
                res.ContentType = "application/json";
                res             = res.WithHeader("Server-Timing", $"decode;dur={decodeTime}, solve;dur={solveTime}, encode;dur={encodeTime}");
                if (definition.HasErrors)
                {
                    res.StatusCode = Nancy.HttpStatusCode.InternalServerError;
                }
                else
                {
                    if (input.CacheSolve)
                    {
                        DataCache.SetCachedSolveResults(body, returnJson, definition);
                    }
                }
                return(res);
            }
        }
Exemple #16
0
 public static void SetCachedDefinition(string key, GrasshopperDefinition definition)
 {
     System.Runtime.Caching.MemoryCache.Default.Set(key, definition, CachePolicy);
 }