3d-force-graph-vr

repository·master·Indexed 42 days ago

https://github.com/vasturiano/3d-force-graph-vr

A web component for visualizing complex graph data structures in Virtual Reality (VR), combining A-Frame for rendering and d3-force-3d for physics-based layout calculations. Version 3.1.2.

Tokens
2.4K
Snippets
6
Records
13
Agent score
53%

What's inside 3d-force-graph-vr

  1. Install and import 3d-force-graph-vr

    master

    You can include 3d-force-graph-vr in your project using either an ES module import or a CDN script tag.

    // ES Module import
    import ForceGraphVR from '3d-force-graph-vr';
    <!-- Script tag usage -->
    <script src="//cdn.jsdelivr.net/npm/3d-force-graph-vr"></script>
  2. Quick start with 3d-force-graph-vr

    master

    To use 3d-force-graph-vr, you must first ensure that A-Frame is loaded in your application. You can then initialize the graph by importing the module or using a script tag, and passing a DOM element to the ForceGraphVR constructor. Use the .graphData() method to provide your graph data.

    Requirements:

    • A-Frame must be loaded via a script tag for the VR rendering to function.

    Steps:

    1. Load A-Frame.
    2. Load 3d-force-graph-vr.
    3. Instantiate ForceGraphVR with a target DOM element.
    4. Call .graphData(myData) to render the graph.
    <!-- 1. Load A-Frame -->
    <script src="//cdn.jsdelivr.net/npm/aframe"></script>
    
    <!-- 2. Load 3d-force-graph-vr -->
    <script src="//cdn.jsdelivr.net/npm/3d-force-graph-vr"></script>
    
    <script>
      // 3. Initialize and provide data
      const myGraph = new ForceGraphVR(document.querySelector('#my-element'))
        .graphData(myData);
    </script>
  3. Style Links in the Graph

    master

    Links (lines/cylinders) can be styled using attributes or accessor functions.

    Key styling options:

    • linkLabel(str|fn): Name shown in the label (default: 'name').
    • linkDesc(str|fn): Description shown under the label (default: 'desc').
    • linkColor(str|fn): Line color (default: 'color').
    • linkOpacity(num): Line opacity between [0, 1] (default: 0.2).
    • linkWidth(num|str|fn): Line width. A value of 0 renders a constant 1px ThreeJS Line.
    • linkCurvature(num|str|fn): Curvature radius. 0 is straight, 1 is a semi-circle. Positive values curve clockwise, negative counter-clockwise.
    • linkMaterial(Material|str|fn): Custom ThreeJS Material. Defaults to MeshLambertMaterial.
    • linkThreeObject(Object3d|str|fn): Custom ThreeJS Object3d for the link.
    • linkDirectionalArrowLength(num|str|fn): Length of the arrow head indicating direction (default: 0).
    • linkDirectionalParticles(num|str|fn): Number of particles traveling along the link to show direction (default: 0).
  4. Style Nodes in the Graph

    master

    Nodes can be styled using attributes or accessor functions. Most methods accept a string (attribute name), a number/boolean, or a function fn(node).

    Key styling options:

    • nodeVal(num|str|fn): Determines the numeric value of a node, which affects its sphere volume (default: 'val').
    • nodeLabel(str|fn): The name shown in the label (default: 'name').
    • nodeDesc(str|fn): The description shown under the label (default: 'desc').
    • nodeColor(str|fn): The color of the sphere (default: 'color').
    • nodeAutoColorBy(str|fn): Automatically groups colors by an attribute (e.g., 'type') for nodes without a specific color.
    • nodeOpacity(num): Sphere opacity between [0, 1] (default: 0.75).
    • nodeResolution(num): Geometric resolution (segments per circumference). Higher is smoother (default: 8).
    • nodeThreeObject(Object3d|str|fn): Provide a custom ThreeJS Object3d to render instead of the default sphere.
    • nodeThreeObjectExtend(bool|str|fn): If true, the custom object extends the default sphere; if false, it replaces it (default: false).
  5. Configure Container Layout and Background

    master

    Control the visual container of the VR canvas using these methods:

    • width(px) / height(px): Set the canvas dimensions.
    • backgroundColor(str): Set the chart background color (default: #000011).
    • showNavInfo(boolean): Toggle the visibility of the navigation controls footer info (default: true).
  6. Get the Graph Bounding Box

    master

    Use getGraphBbox([nodeFilterFn]) to retrieve the current bounding box of the nodes.

    Returns an object: { x: [min, max], y: [min, max], z: [min, max] }.

    If you want the bounding box of only a specific subset of nodes, pass a filter function: node => node.type === 'important'.

  7. Handle Node and Link Interactions

    master

    Register callback functions to respond to user interactions:

    • onNodeHover(fn): Called on node hover. fn(node, prevNode).
    • onLinkHover(fn): Called on link hover. fn(link, prevLink).
    • onNodeClick(fn): Called on node click. fn(node).
    • onLinkClick(fn): Called on link click. fn(link).
  8. Configure the Force Engine and Simulation

    master

    The graph uses a force-directed simulation. You can choose between d3 and ngraph engines.

    Engine Selection:

    • forceEngine(str): Set to 'd3' (default) or 'ngraph'.

    DAG (Directed Acyclic Graph) Layout: If your graph is a DAG, you can apply layout constraints:

    • dagMode(str): Options include 'td' (top-down), 'bu' (bottom-up), 'lr' (left-to-right), 'rl' (right-to-left), 'zout', 'zin', 'radialout', or 'radialin'.
    • dagLevelDistance(num): Distance between graph depths.
    • dagNodeFilter(fn): Function fn(node) to return true if the node should be included in the DAG layout.
    • onDagError(fn): Callback for when a cycle is encountered. By default, this throws an exception.

    D3 Specific Configuration (only if forceEngine is 'd3'):

    • d3Force(str, [fn]): Configure or add internal forces (e.g., 'link', 'charge', 'center').
    • d3AlphaMin(num): Simulation alpha min.
    • d3AlphaDecay(num): Simulation intensity decay.
    • d3VelocityDecay(num): Medium resistance.
    • d3ReheatSimulation(): Resets alpha to 1 to restart simulation.

    General Simulation Control:

    • warmupTicks(int): Number of dry-run cycles before rendering (default: 0).
    • cooldownTicks(int): Number of frames to render before freezing (default: Infinity).
    • cooldownTime(num): Time in ms to render before freezing (default: 15000).
    • onEngineTick(fn): Called at every tick.
    • onEngineStop(fn): Called when the engine stops/freezes.
    • refresh(): Redraws all nodes and links.
  9. Configure Data Input for the Graph

    master

    You can provide graph data to the engine using graphData or by providing a URL to a JSON file via jsonUrl.

    To use graphData, provide an object following this structure:

    {
        "nodes": [ 
            { "id": "id1", "name": "name1", "val": 1 },
            { "id": "id2", "name": "name2", "val": 10 }
        ],
        "links": [
            { "source": "id1", "target": "id2" }
        ]
    }

    If your data uses different keys for identifiers, you can customize the accessors:

    • nodeId(str): The attribute for unique node IDs (default: 'id').
    • linkSource(str): The attribute in link objects referring to the source node ID (default: 'source').
    • linkTarget(str): The attribute in link objects referring to the target node ID (default: 'target').
    graphInstance.graphData({ nodes: [...], links: [...] });
    // OR
    graphInstance.jsonUrl('https://example.com/data.json');
  10. Import the 3D Force-Graph VR library

    master

    The 3d-force-graph-vr package provides a default export that serves as the main entry point for creating 3D force-directed graphs in Virtual Reality. You can import the library directly from the package root. The package also automatically imports its required CSS styles.

    import ForceGraphVR from '3d-force-graph-vr';
    
    // Usage typically involves passing a DOM element to the constructor
    const Graph = ForceGraphVR()(document.getElementById('graph-container'));
  11. Set labels and descriptions for nodes and links

    master

    Use accessor methods to define what text is displayed for nodes and links. Accessors can be a direct value, a string representing a key in the object, or a callback function (obj) => value.

    • nodeLabel(accessor): Sets the label for nodes.
    • nodeDesc(accessor): Sets the description for nodes.
    • linkLabel(accessor): Sets the label for links.
    • linkDesc(accessor): Sets the description for links.

    ObjAccessor<T, InT> allows you to pass a string key (e.g., 'name') or a function (e.g., node => node.name).

    // Using string keys
    graph.nodeLabel('name').nodeDesc('details');
    
    // Using accessor functions
    graph.nodeLabel(node => `${node.id} (${node.group})`);