Connection to the HOOPS Server

Summary

In this section, we will show how to request a viewing session and stream a model into your application via the HOOPS Server.

Normally, the infrastructure to facilitate the on-demand streaming will be sitting behind a proxy on the internet or within a corporate network. For this simplified example, we are taking advantage of the local HOOPS Server that is bundled with the HOOPS Visualize Web package and that you have already used to view the quick-start samples in the first section.

Note

Among the main benefits of HOOPS Visualize Web are the capabilities to: 1) quickly stream massive models to the client, 2) request subsets of a model on-demand, and 3) render a model completely server-side. All of this functionality requires a Stream Cache Server to be spawned for every viewing session, which handles the view-dependent streaming and keeps interacting with the Web Viewer component as long as the viewing session is active. To manage and monitor those viewing sessions, we provide a Node.js-based framework simply called the HOOPS Server.

Concepts

  • Requesting a session from the HOOPS Server
  • Starting a Stream Cache Server
  • Creating <hoops-web-viewer> dynamically once a value it needs isn’t known upfront

Running the Server

If you are not already running the server, start it by navigating to the quick_start directory of the installation and running start_server.bat/sh. You should see a console window with status information indicating that the server is up and its services are listening on specific ports.

Requesting a Viewing Session

Now, let’s write some code that connects your application to this server. First, we start with a new file called src/ServerConnection.ts which we fill with the class below:

// src/ServerConnection.ts
export class ServerConnection {
        private readonly _endpoint: string;

        constructor(endpoint: string) {
                this._endpoint = endpoint;
        }

        connect(): Promise<string> {
                const request = new XMLHttpRequest();
                request.open('POST', this._endpoint + '/api/spawn');
                request.overrideMimeType('application/json');
                request.setRequestHeader('Content-Type', 'application/json');
                request.timeout = 60000;

                return new Promise((resolve, reject) => {
                        request.onreadystatechange = () => {
                                if (request.readyState === 4) {
                                        if (request.status === 200) {
                                                resolve(this.parseServerSuccessResponse(request.responseText));
                                        } else {
                                                reject(new Error("Couldn't connect to the HOOPS Server"));
                                        }
                                }
                        };

                        request.send('{"class":"csr_session","params":{}}');
                });
        }

        private parseServerSuccessResponse(text: string): string {
                const jsonResponse = JSON.parse(text);
                return jsonResponse.endpoints['ws'];
        }
}

The only purpose of this class is to make a standard HTTP POST request to the HOOPS Server at the endpoint to request a viewing session and wrap this request into a promise that resolves with the websocket endpoint of the viewing session that has been reserved for this request. Please see the Programming Guide for more info on the HOOPS Server REST API.

Note

Every HOOPS Server supports a large number of simultaneous viewing sessions each assigned to their own port. In a real-world web application requesting those sessions would not be done directly via the client-side JS code but instead within your server application, most likely utilizing a reverse-proxy setup for security reasons and to ensure that all WebSockets traffic goes through standard ports.

See the Programming Guide for more information.

Import ServerConnection in src/main.ts the same way we’ve imported the other classes we’ve written in this tutorial:

import { ServerConnection } from './ServerConnection';

Creating the Web Viewer Once the Endpoint Is Known

So far in this tutorial, <hoops-web-viewer> has always been written directly into index.html, with its endpointUri known upfront. That doesn’t work here: the endpoint we need to connect to only exists after ServerConnection.connect() resolves, and <hoops-web-viewer> only reads its endpointUri (and model, and every other configuration property) once, the first time it renders - changing those properties afterwards has no effect, since that’s also the moment it constructs and starts the underlying viewer. So for this page, we deviate from the static-HTML pattern used throughout the rest of this tutorial: leave <hoops-web-viewer> out of index.html entirely, and create it once we have somewhere to point it.

Remove the <hoops-web-viewer> line from index.html, keeping the surrounding context manager and toolbar buttons in place:

<hoops-service-registry>
        <hoops-web-viewer-context-manager id="context-manager">
                <hoops-toolbar-camera-operator></hoops-toolbar-camera-operator>
                <hoops-toolbar-drawmode></hoops-toolbar-drawmode>
        </hoops-web-viewer-context-manager>
</hoops-service-registry>

Note

It’s safe to leave <hoops-web-viewer> out initially - <hoops-toolbar-camera-operator> and the other context-consuming components subscribe to the context manager’s state and pick up the WebViewer reactively whenever it becomes available, even if that happens well after the page has loaded.

Now, in src/main.ts, request a session and create the viewer element once we know where to point it. Since index.html no longer has a static <hoops-web-viewer> tag, the module-level viewerEl constant from Hello Web Viewer no longer resolves to anything on this page - the viewerEl below is a new, locally-scoped variable for the element we’re about to create:

import { Color } from '@ts3d-hoops/web-viewer';
import type { WebViewerComponent } from '@ts3d-hoops/web-viewer-components';
import { ServerConnection } from './ServerConnection';

// contextManagerEl already exists - it was declared in Custom Operator Basics

const server = new ServerConnection('http://localhost:11182');
server.connect().then((endpointUri) => {
        const viewerEl = document.createElement('hoops-web-viewer') as HTMLElement & WebViewerComponent;
        viewerEl.id = 'viewer';
        viewerEl.endpointUri = endpointUri;
        viewerEl.model = 'moto';

        viewerEl.addEventListener('hwvSceneReady', ({ detail: { hwv } }) => {
                hwv.view.setBackgroundColor(Color.blue(), Color.white());
        });

        viewerEl.addEventListener('hwvModelStructureReady', ({ detail: { hwv } }) => {
                document.getElementById('ModelStructureReady')!.innerHTML = 'Model Structure Ready';
                webViewer = hwv;
                modelTreeEl.model = hwv.model;
        });

        viewerEl.addEventListener('hwvCamera', ({ detail: { camera } }) => {
                document.getElementById('CameraData')!.innerHTML = JSON.stringify(camera.toJson(), null, 4);
        });

        viewerEl.addEventListener('hwvSelectionArray', ({ detail: { selectionEvents } }) => {
                modelTreeEl.selected = selectionEvents.map((selectionEvent) => selectionEvent.getSelection().getNodeId());
        });

        contextManagerEl.prepend(viewerEl);
});

We start by initializing our new class with the port that the demo server in our package is listening to. After the POST request has successfully resolved, we create the <hoops-web-viewer> element, set its endpointUri property to the websocket endpoint we were given, and set its model property separately to specify the model we want to load. Again, we are not loading the scs file we have copied to our application directory anymore but this time the referenced SC model (which happens to be a shattered model) will be streamed via a websocket connection from the Stream Cache Server.

The four event listeners re-attach the same behaviors we built up over the course of this tutorial - background color, the “Model Structure Ready” message and model tree population from Registering Callbacks and Interacting with the Model Tree, the camera readout, and bidirectional selection - to this dynamically created element, since none of that wiring can happen until the element exists. Finally, contextManagerEl.prepend(viewerEl) inserts it into the page. That insertion is what triggers firstUpdated() internally, which is when the properties we just set are read and the underlying WebViewer is actually constructed and started.

After this modification to the startup code, the Web Viewer component is now ready for streaming models via the HOOPS Server. No further modifications are required.

We only scratched the surface with this example. Implementing a viewing infrastructure on your server-backend that can scale to many simultaneous users is not an easy task and requires considerable web-expertise even when using web platforms like AWS or Azure. However, it is often worth the effort, in particular, if your models are large and/or you want to provide your user with a consistent experience across all devices.

Please see the Programming Guide for more information about server setup.

Thank you for taking the time to read through this tutorial with HOOPS Visualize Web. We recommend continuing your training by visiting our Tutorials section. You will find information about setting up your local development environment for HOOPS Visualize Web, as well as more tutorials that explore real-world problems that HOOPS Visualize Web can solve for your company.