Best approach working with multiple objects?

Hello.
I’m working with a lot of objects in one drawing (5k+). There are multiple independent sections that can be worked on separately. Objects in each section share layers, so I can’t use layers to hide certain sections.

My current approach is to isolate a section and work with it, however I often need to isolate part of that section as well, but that creates an issue since I don’t know how to restore visibility of last hidden batch only…it restores visibility of all objects and I have to isolate the whole section again.

We can create a named set when hiding objects, and then restore that set only with -show blah, but is there a way to isolate objects in named sets? (in my flow it’s easier to highlight objects I want to work with rather objects I want to hide).

Any suggestion how to more efficiently work with multiple sections in one drawing?

Thank you

For now I’m satisfied with this little script that isolates into set selected curves. Essentially it inverts selection and executes -hide <setname>
And a complimentary Show.py that also shows named sets as options and if no name supplied restores all named sets only, leaving all other hidden objects hidden.
Isolate.py (2.1 KB)
Show.py (8.6 KB)

Isolate.py
"""
Isolate.py

Version: 26.7.22.1837

Isolate selected objects by hiding all other visible normal objects.

The named set, when supplied, is assigned to the objects hidden by isolation.

Alias/button macro:
    !_-RunPythonScript (import rhinoscriptsyntax as rs; g={}; execfile(rs.FindFile("Isolate.py"), g); g["isolate"]())
"""

import Rhino
import Rhino.Input as ri
import Rhino.Input.Custom as ric
import rhinoscriptsyntax as rs


VERSION = "26.7.22.1837"
_SET_PROMPT = "Name of object set to isolate. Press Enter to isolate with no named set."


def _get_set_name():
    getter = ric.GetString()
    getter.SetCommandPrompt(_SET_PROMPT)
    getter.AcceptNothing(True)

    result = getter.Get()
    if result == ri.GetResult.Nothing:
        return ""
    if result == ri.GetResult.String:
        return (getter.StringResult() or "").strip()
    return None


def isolate():
    isolate_ids = rs.SelectedObjects(include_lights=False, include_grips=False) or []
    if not isolate_ids:
        isolate_ids = rs.GetObjects(
            "Select objects to isolate",
            group=True,
            preselect=True,
            select=True,
        ) or []

    if not isolate_ids:
        return

    isolate_ids = list(isolate_ids)
    isolate_set = set(isolate_ids)
    to_hide = [
        object_id
        for object_id in (rs.NormalObjects() or [])
        if object_id not in isolate_set
    ]

    if not to_hide:
        Rhino.RhinoApp.WriteLine("Isolate: nothing to hide.")
        return

    set_name = _get_set_name()
    if set_name is None:
        return

    safe_name = set_name.replace('"', "'")
    command = '_-Hide "{}"'.format(safe_name) if safe_name else "_-Hide _Enter"

    redraw = rs.EnableRedraw(False)
    try:
        rs.UnselectAllObjects()
        rs.SelectObjects(to_hide)
        success = rs.Command(command, False)
    finally:
        rs.UnselectAllObjects()
        rs.SelectObjects(isolate_ids)
        rs.EnableRedraw(redraw)

    if not success:
        Rhino.RhinoApp.WriteLine("Isolate: Rhino Hide command failed.")


if __name__ == "__main__":
    isolate()
Show.py
"""
show.py

Version: 26.7.24.1119

Show objects from one named Rhino hide set, or press Enter to show every
named set. Ordinary hidden objects remain hidden.

Alias/button macro:
    !_-RunPythonScript (import rhinoscriptsyntax as rs; g={}; execfile(rs.FindFile("show.py"), g); g["show"]())
"""

import clr
import Rhino
import Rhino.Input as ri
import Rhino.Input.Custom as ric
import scriptcontext as sc

from System import Array, IntPtr, Object
from System.Reflection import BindingFlags
from Rhino.Runtime.InteropWrappers import StringHolder


VERSION = "26.7.24.1119"
_PROMPT = "Name of object set to show. Press Enter to show all named sets."
_MAX_OPTIONS = 20


def _find_native_methods():
    try:
        object_type = clr.GetClrType(Rhino.DocObjects.RhinoObject)
        pointer = object_type.GetMethod(
            "ConstPointer",
            BindingFlags.Instance | BindingFlags.NonPublic,
        )

        assembly = clr.GetClrType(Rhino.RhinoApp).Assembly
        unsafe_type = assembly.GetType("UnsafeNativeMethods", False)
        if unsafe_type is None:
            return None, None, None

        flags = BindingFlags.Static | BindingFlags.NonPublic
        get_name = unsafe_type.GetMethod(
            "CRhinoObject_AttachHideGetName",
            flags,
        )
        remove_name = unsafe_type.GetMethod(
            "CRhinoObject_RemoveHideName",
            flags,
        )
        return pointer, get_name, remove_name
    except Exception:
        return None, None, None


_POINTER_METHOD, _GET_NAME_METHOD, _REMOVE_NAME_METHOD = _find_native_methods()


def _arguments(*values):
    return Array[Object](list(values))


def _pointer(rhino_object):
    if _POINTER_METHOD is None:
        return IntPtr.Zero

    try:
        value = _POINTER_METHOD.Invoke(rhino_object, None)
        return value if value is not None else IntPtr.Zero
    except Exception:
        return IntPtr.Zero


def _hide_set_name(rhino_object):
    pointer = _pointer(rhino_object)
    if pointer == IntPtr.Zero or _GET_NAME_METHOD is None:
        return None

    holder = StringHolder()
    try:
        found = _GET_NAME_METHOD.Invoke(
            None,
            _arguments(pointer, holder.NonConstPointer()),
        )
        if not found:
            return None

        name = holder.ToString() or ""
        return name if name else None
    except Exception:
        return None
    finally:
        holder.Dispose()


def _remove_hide_set_name(rhino_object):
    pointer = _pointer(rhino_object)
    if pointer == IntPtr.Zero or _REMOVE_NAME_METHOD is None:
        return False

    try:
        return bool(_REMOVE_NAME_METHOD.Invoke(None, _arguments(pointer)))
    except Exception:
        return False


def _native_access_available():
    return all(
        method is not None
        for method in (_POINTER_METHOD, _GET_NAME_METHOD, _REMOVE_NAME_METHOD)
    )


def _is_internal_name(name):
    return len(name) >= 4 and name.startswith("$$") and name.endswith("$$")


def _is_hidden(rhino_object):
    return bool(
        rhino_object.IsHidden
        or rhino_object.Attributes.Mode == Rhino.DocObjects.ObjectMode.Hidden
    )


def _named_sets(document):
    settings = Rhino.DocObjects.ObjectEnumeratorSettings()
    settings.NormalObjects = True
    settings.LockedObjects = False
    settings.HiddenObjects = True
    settings.IdefObjects = False
    settings.DeletedObjects = False
    settings.ActiveObjects = True
    settings.ReferenceObjects = False
    settings.IncludeLights = True
    settings.IncludeGrips = False
    settings.IncludePhantoms = False
    settings.VisibleFilter = False

    sets = {}
    for rhino_object in document.Objects.GetObjectList(settings):
        if not _is_hidden(rhino_object):
            continue

        name = _hide_set_name(rhino_object)
        if not name or _is_internal_name(name):
            continue

        key = name.lower()
        hide_set = sets.get(key)
        if hide_set is None:
            hide_set = {
                "name": name,
                "order": int(rhino_object.RuntimeSerialNumber),
                "ids": [],
            }
            sets[key] = hide_set

        hide_set["order"] = max(
            hide_set["order"],
            int(rhino_object.RuntimeSerialNumber),
        )
        hide_set["ids"].append(rhino_object.Id)

    return sorted(
        sets.values(),
        key=lambda item: (item["order"], item["name"].lower()),
    )


def _normalize(value):
    value = (value or "").strip()
    if len(value) >= 2 and (
        (value[0] == '"' and value[-1] == '"')
        or (value[0] == "'" and value[-1] == "'")
    ):
        return value[1:-1].strip()
    return value


def _is_ascii_letter(value):
    return ("A" <= value <= "Z") or ("a" <= value <= "z")


def _option_name(set_name, position, used):
    base = "".join(
        character
        for character in set_name
        if _is_ascii_letter(character) or ("0" <= character <= "9")
    )
    if not base or not _is_ascii_letter(base[0]):
        base = "Set{}".format(position)

    name = base
    suffix = 2
    while name.lower() in used:
        name = "{}{}".format(base, suffix)
        suffix += 1

    used.add(name.lower())
    return name


def _get_set_name(named_sets):
    getter = ric.GetString()
    try:
        getter.SetCommandPrompt(_PROMPT)
        getter.AcceptNothing(True)
        getter.EnableTransparentCommands(True)

        options = {}
        used = set()
        for position, hide_set in enumerate(named_sets[:_MAX_OPTIONS], 1):
            set_name = hide_set["name"]
            option_name = _option_name(set_name, position, used)
            option_index = (
                getter.AddOption(option_name)
                if option_name == set_name
                else getter.AddOption(option_name, set_name)
            )
            if option_index > 0:
                options[option_index] = set_name

        result = getter.Get()
        if getter.CommandResult() != Rhino.Commands.Result.Success:
            return None
        if result == ri.GetResult.Nothing:
            return ""
        if result == ri.GetResult.String:
            return _normalize(getter.StringResult())
        if result == ri.GetResult.Option:
            option = getter.Option()
            return options.get(option.Index) if option is not None else None
        return None
    finally:
        getter.Dispose()


def _capture_selection(document):
    if Rhino.RhinoApp.InCommand <= 1:
        return None

    snapshot = []
    for rhino_object in document.Objects.GetSelectedObjects(True, True):
        state = rhino_object.IsSelected(True)
        if state:
            snapshot.append(
                (
                    rhino_object,
                    state in (1, 2),
                    state == 2,
                    list(rhino_object.GetSelectedSubObjects() or []),
                )
            )
    return snapshot


def _restore_selection(document, snapshot):
    if snapshot is None:
        return

    document.Objects.UnselectAll()
    for rhino_object, whole_object, persistent, sub_objects in snapshot:
        if whole_object:
            rhino_object.Select(True, True, persistent, True, True, True)
        for component_index in sub_objects:
            rhino_object.SelectSubObject(component_index, True, True, False)

    document.Views.Redraw()


def _show(document):
    if not _native_access_available():
        Rhino.RhinoApp.WriteLine("Named hide-set access is unavailable.")
        return

    named_sets = _named_sets(document)
    requested_name = _get_set_name(named_sets)
    if requested_name is None:
        return

    show_all = not requested_name
    object_ids = [
        object_id
        for hide_set in named_sets
        if show_all or hide_set["name"].lower() == requested_name.lower()
        for object_id in hide_set["ids"]
    ]

    if not object_ids:
        description = (
            "any named set" if show_all else "set {}".format(requested_name)
        )
        Rhino.RhinoApp.WriteLine(
            "No hidden objects in {}.".format(description)
        )
        return

    shown = 0
    for object_id in object_ids:
        if not document.Objects.Show(object_id, False):
            continue

        shown += 1
        rhino_object = document.Objects.FindId(object_id)
        if rhino_object is not None:
            _remove_hide_set_name(rhino_object)

    document.Views.Redraw()
    Rhino.RhinoApp.WriteLine("Shown {} object(s).".format(shown))


def show():
    document = sc.doc
    selection = _capture_selection(document)
    try:
        _show(document)
    finally:
        _restore_selection(document, selection)


if __name__ == "__main__":
    show()

Isolate_BlueGrey Isolate_A_BlueGrey Isolate_B_BlueGrey Isolate_C_BlueGrey Isolate_BlueYellow

Hi vano_artful,

Nice script, that inverted-selection + named -Hide approach is exactly the right way to fake “isolate a named set” — Rhino doesn’t have a native isolate-this-batch-and-restore-just-it, so hiding the complement under a name is the trick.

On the “restore brings back everything” pain: that’s expected. Show/Unisolate reveal all hidden objects, there’s no last-batch undo. Named hide sets are the fix, which you already found — -Hide sectionA, then -Hide sectionA_detail for the sub-batch, and -Show sectionA_detail peels back just that last batch.

One thing to add to your flow, since you like highlighting what to keep — Named Selections (Rhino 8, NamedSelections panel):

  1. Select a section once and save it as a named selection.
  2. To work it: click the named selection to select, then Isolate (or run your script).
  3. Sets are stored in the 3dm, so they persist across sessions.

That way you don’t have to hand-pick the keep-set every time — pick the named selection, then isolate. One gotcha: if you ever turn a section into a block it drops out of its named selection.

Thank you. The named selection is very useful tool when you work with “fixed” number of objects. In my workflow it definitely will be very useful!

I’ve added Show.py script that makes it even easier work with named hidden sets.