# Castle Model Viewer (formerly view3dscene)
include::common.adoc[]
:description: Viewer for 3D and 2D model formats supported by Castle Game Engine: glTF, X3D, VRML, MD3, OBJ, STL, PLY, Collada, Spine JSON, sprite sheets (and more). Supports viewing the scene in the "Examine" mode and walking in the virtual world with collision detection and gravity. Many 3D graphic effects are available like mirrors, shadows, shaders. We can also convert between some model formats. Free and open-source software. For Linux, Windows, macOS, Raspberry Pi and more.
:cge-social-share-image: view3dscene_outlines.png

== Introduction

// Viewer for link:model_formats[all 3D and 2D model formats supported by the Castle Game Engine]:

// [role="compact"]
// - link:gltf[glTF]
// - link:x3d[X3D]
// - link:x3d[VRML]
// - link:ifc[IFC]
// - link:spine[Spine JSON]
// - link:sprite_sheets[sprite sheets (in Castle Game Engine, Cocos2D and Starling XML formats)]
// - link:md3[MD3]
// - Wavefront OBJ
// - 3DS
// - STL
// - PLY
// - Collada
// - link:model_formats[and more].

Viewer for link:model_formats[3D and 2D model formats supported by the Castle Game Engine]: link:gltf[glTF], link:x3d[X3D], link:x3d[VRML], link:ifc[IFC], link:spine[Spine JSON], link:sprite_sheets[sprite sheets (in Castle Game Engine, Cocos2D and Starling XML formats)], link:md3[MD3], Wavefront OBJ, 3DS, STL, PLY, Collada, link:model_formats[and more].

Examine or walk in the virtual world with collisions, gravity, animations, X3D sensors, shadows, mirrors, shaders and more. View it from multiple cameras at once. Take screenshots with various options (transparent background, cube maps).

You can also convert between model formats -- right now you can convert any model to X3D or STL, we plan to add output to glTF soon as well. Together with this application, we also distribute link:castle-model-converter[castle-model-converter] command-line tool and you can also use our link:convert.php[online model converter]. They all use the same codebase and have the same features.

// view3dscene_outlines.png credits:
//
// The scene is by Luis Fernandez, downloaded from Sketchfab -
// https://sketchfab.com/3d-models/ftm-0970f30574d047b1976ba0aa6f2ef855 .
//
// Find more of his work on
// https://sketchfab.com/luyssport ,
// https://www.artstation.com/artwork/8zYgE ,
// https://www.artstation.com/artwork/oB5qz .

cgeimg::block[
  castle_model_viewer_cat_duelist.png|Artstation Challenge - Untamed - Cat Duelist by Marc_A_D\, from Sketchfab - https://sketchfab.com/3d-models/artstation-challenge-untamed-cat-duelist-5bec11c3160048f7a8ce482523ac2deb,
  castle_model_viewer_cat_duelist_wireframe.png|(Wireframe View) Artstation Challenge - Untamed - Cat Duelist by Marc_A_D\, from Sketchfab - https://sketchfab.com/3d-models/artstation-challenge-untamed-cat-duelist-5bec11c3160048f7a8ce482523ac2deb,
  view3dscene_outlines.png|Castle Model Viewer (by Luis Fernandez\, https://sketchfab.com/3d-models/ftm-0970f30574d047b1976ba0aa6f2ef85 ),
  //view3dscene_mousey.png|glTF scene with Mixamo animations,
  //view3dscene_steampunk_gltf.png|Steampunk glTF scene,
  //view3dscene_spine_ffd_animation.png|Spine Free-Form Deformation animated,
  //view3dscene_spine_roseanne.png|Animated 2D Spine creature,
  //view3dscene_dungeon_multiple_views.png|Multiple views at the same 3D dungeon
]

== Download

=== Stable version (5.2.0)

cge::download-application[
  5.2.0,
  v5.2.0,
  castle-engine,
  castle-model-viewer,
  castle-model-viewer,
    win64-x86_64;
    //win32-i386;
    linux-x86_64;
    linux-arm;
    linux-aarch64;
    darwin-x86_64
]

No installation is necessary. Just download and unpack these archives wherever you want, and run the `castle-model-viewer` program inside.

Platform-specific notes:

macOS::
Our application is not signed and it will be placed in a "quarantine" by default. Execute command like `xattr -cr ~/Downloads/castle-model-viewer.app` to remove the quarantine. See link:macos[macOS support] for more information.

Linux, FreeBSD::
To hear 3D sound in X3D worlds, install also link:openal[OpenAL] and http://xiph.org/vorbis/[VorbisFile] libraries using your package manager.

////
Too much info:

Above recommends to download a snapshot, 4.3.0, automatically updated after every commit. The last https://github.com/castle-engine/castle-model-viewer/releases/tag/v4.2.0[stable release (version 4.2.0) is here] but it's quite old at this point.
////

NOTE: If you already have link:/[Castle Game Engine], then just run `castle-model-viewer` executable from the engine `bin` subdirectory. There's no need to download this separately.

NOTE: We also recommend to download link:demo_models[our collection of demo models]!

[#snapshot]
=== Snapshot (unstable, preview of the next version) (5.3.0)

cge::download-application[
  5.3.0,
  snapshot,
  castle-engine,
  castle-model-viewer,
  castle-model-viewer,
    win64-x86_64;
    //win32-i386;
    linux-x86_64;
    linux-arm;
    linux-aarch64;
    darwin-aarch64;
    darwin-x86_64
]

NOTE: If you find a bug, https://github.com/castle-engine/castle-model-viewer/issues[please report it here]. Thank you!

////
Below is no longer actively tested, and was complicated to use, for now don't expose docs of it:

==== Optionally install GNOME (and other freedesktops) integration

If you use GNOME, MATE or other desktops following
http://freedesktop.org/[freedesktop.org] specifications,
you can optionally install also a desktop file to have application
available in your menu / dashboard, with a nice icon,
and associate it with all handled model types.

```shell
# Place castle-model-viewer on $PATH, for example like this:
sudo ln -s /usr/local/bin/castle-model-viewer castle-model-viewer

# Install menu items, icons, mime types:
cd desktop/
./install.sh
```

You may need to logout and login again to your GNOME/desktop
session for all programs to catch up (alternatively, you can do
`killall gnome-panel &amp;&amp; killall nautilus`
but this is obviously somewhat brutal method).

If you use GNOME file manager Nautilus there's
one more cool thing you can do: use
castle-model-viewer to *generate on-the-fly thumbnails of 3D models*
in the viewed directory. Assuming that castle-model-viewer is on the $PATH
and you already did previous `./install.sh`, you can run:

```shell
./install_thumbnailer.sh
```

<!--inside the `desktop` directory.-->
This will add the gconf keys to run thumbnailers on your 3D models.
Enter some directory with VRML / X3D / other 3D files,
and enjoy your thumbnails :)
_Beware that loading arbitrary 3D scene may take a lot of time,
so using the thumbnailer may consume a lot of memory and CPU power_.
But it seems that thumbnailer is nicely run with appropriate priority,
so it doesn't actually exhaust your cpu.
<!--
Although we try
to be fast, and some things are specially optimized for screenshot,
there are no guarantees. No engine can load arbitrary large
3D data without any noticeable resource use.
Nautilus should automatically terminate thumbnailer that
runs too long, so this is not critical problem. After all, reading large
movies or images has similar problems, but it works quite Ok, right?
(Actually, 3D data is much more difficult than reading just a few starting
seconds of a movie or a simple 2D image...) -->
And the author of this
text is using castle-model-viewer thumbnailer all the time, and it works
flawlessly :) So give it a try!
////

== Navigating with keys and mouse

=== Inspection (in all navigation modes)

Left Mouse Button Click::
Interact with the X3D world, using https://castle-engine.io/x3d_implementation_pointingdevicesensor.php[X3D pointing-device sensors]. Open models in link:demo_models[demo models] (subdirectory https://github.com/castle-engine/demo-models/tree/master/sensors_pointing_device[sensors_pointing_device]) to experience what this means.

Ctrl + Right Mouse Button Click::
Pick a point, selecting a triangle and it's containing shape. Some operations can then act on the selected point / triangle / shape, e.g. _"Help -> Selected Object Information"_ or _"Edit -> Hide Shape"_.

=== Examine Navigation

Left mouse dragging::
Rotate the scene.

Middle mouse dragging (or Left mouse + Shift)::
Move the scene.

Right mouse dragging (or Left mouse + Ctrl; or scroll wheel)::
Zoom the scene.

Arrow keys::
Rotate the scene, by changing rotation speed.

Space::
Stop rotating.

Ctrl + Arrows::
Move the scene.

+ / -::
Scale the scene.

=== Walk and Fly Navigation

Drag up / down with left mouse button::
Move forward / backward.

Drag left / right with left mouse button::
Turn left / right.

Drag right mouse button::
Look around (mouse look).

Mouse wheel::
Zoom in / out (just another way to move forward / backward in this case).

Mouse wheel while right mouse button pressed::
Change moving speed.

W S Up Down::
Move forward / backward.

A D::
Strafe left / right.

Left Right::
Turn left / right.

Space C::
Jump / Crouch (or fly up / down).

Shift::
Hold while moving to run (move with 2x speed).

Insert Delete::
Increase / decrease avatar height (preferred camera height above the ground)

Ctrl + Left Right::
Rotate _slower_ (useful to precisely set the camera).

We also support http://www.3dconnexion.com/[3D mouse devices], see http://www.youtube.com/watch?v=7tV9Qmjgx1U[the demo video about 3D mouse inside castle-model-viewer].

== Command-line options

This is a GUI application and you don't need to use any command-line options.

But you can -- to automate some tasks, like capturing screenshots.

Run with command-line option `--help` to see the full list of options.

In addition to all the options documented below,
also all link:cli_options_window[standard options understood by our GUI programs],
link:openal[standard options understood by our programs using audio]
and link:cli_options_common[standard options understood by all our programs]
are handled. The options may be given in any order.

You can specify a model filename, or URL to load at the command-line. You can combine this with some other options documented below, e.g. to make a screenshot of given model.

=== Capturing screenshots and movies of 3D scenes and animations

You can use command-line options to make a screenshot or record a movie of the loaded scene.

--screenshot TIME FILE-NAME::
Capture a screenshot of the loaded scene and exit.

--screenshot-range TIME-BEGIN TIME-STEP FRAMES-COUNT FILE-NAME::
Capture a series of screenshots of the loaded scene and exit. The output can be a series of images specified like `output_@counter(4).png` (see https://castle-engine.io/x3d_implementation_texturing_extensions.php#section_ext_movie_from_image_sequence[movies from image sequence for details about `@counter(<padding>)` macro]) or a movie file.
+
To save a movie file, `ffmpeg` must be installed. See link:#ffmpeg[ffmpeg] section for details.
+
Movie recorded this way is guaranteed to be captured with stable number of frames per second. This is different than using independent programs to capture rendering output, which generally relies on the system being _"fast enough"_ to be able to render useful number of frames per second, recording them at the same time.
+
We take `FRAMES-COUNT` screenshots. The first screenshot is at time `TIME-BEGIN`, second screenshot is at `TIME-BEGIN + TIME-STEP`, next one is at `TIME-BEGIN + 2 * TIME-STEP` etc.

--screenshot-transparent::
Make screenshots taken have a transparent background.

Together with one of these 2 options, you definitely want to pass also a model file to load, otherwise we'll just make a screenshot of the default empty (black) scene.

==== Examples

Take a simple screenshot of a scene, at it's default camera:

```shell
castle-model-viewer my_model.gltf --screenshot 0 output.png
```

You can also take multiple screenshots or even multiple movies in a single run. For this, just use the above options multiple times.

Make a movie of 2 seconds of animation, with 25 frames per second:

```shell
castle-model-viewer my_model.castle-anim-frames --screenshot-range 0 0.04 50 output_@counter(4).png
```

Capture 2 movies from the same animation:

```shell
castle-model-viewer my_model.castle-anim-frames \
  --screenshot-range 0 0.04 50 output_@counter(4).avi \
  --screenshot-range 10 0.04 50 output_@counter(4).avi
```

This generates two files: `output1.avi` with 2 second animation from 0.0 to 2.0 time, and `output2.avi` with 2 second animation from 10.0 to 12.0 time.

==== Hints

- To control the camera of your screenshot, place initial camera information in the model (glTF, X3D, VRML, Collada support this).
+
You can use `--viewpoint` command-line option (see below) to choose a specific named viewpoint for screenshot.
+
You can generate wanted `Viewpoint` node also by using `castle-model-viewer`, just set your camera (in interactive mode) the way you like and use menu item _"Clipboard -> Print Current Camera..."_.

- X3D has also the `Background` node to control the color or textures of the skybox.

- To control the size of resulting screenshot, use `--geometry` command-line parameter (documented in link:cli_options_window[standard options understood by our GUI programs]).

- To make your screenshot look best, you may want to use anti-aliasing, see `--anti-alias` option below.

////
For now hidden, too much information:

=== Taking screenshots on a stripped-down Unix server

You need to install a graphic environment
    (that is, _X Windows_ and _OpenGL_) on your server. Even in batch mode,
    we still use OpenGL to grab the screenshot images
    (because using off-screen Mesa or our toy ray-tracer doesn't result
    in a really nice output; we really want OpenGL for all those GLSL effects
    and such).<!-- Which means that all that GUI stuff must be installed
    and working on your server.-->

    Normally, you also need _GTK_ libraries installed.
    However, you can compile from sources a version of castle-model-viewer that doesn't
    need these libraries, and directly accesses XWindows. It will miss
    a menu bar and some other nice GUI stuff, but that's not a problem if you only
    want to run it in batch mode for screenshots. To do this:


- Download the sources of
        castle_game_engine and castle-model-viewer

        Unpack them, such that `castle_game_engine/` and `castle-model-viewer/`
        directories are siblings.
- In the terminal, do
```shell
export CASTLE_FPC_OPTIONS=-dCASTLE_WINDOW_XLIB
cd castle-model-viewer/
make
# and copy resulting castle-model-viewer binaries wherever you want
```

    On a server, you probably want to initialize taking a screenshot
    from a script, and your script isn't necessarily running within the X server.
    There are basically two solutions to this:
    <!--
    Note that the instructions below are not really specific to castle-model-viewer,
    the same concepts work with any X program.-->


- You can keep the X server running continuously,
        and keep your user logged in to the X server,
        and instruct castle-model-viewer to connect to your running X server.
        You do this by adding `--display=:0` option
        to the castle-model-viewer command-line (where `:0` is a common example; for details,
        see X manuals). Or you can set and export the `DISPLAY`
        environment variable, like `export DISPLAY=:0`.

        Unfortunately, this method sometimes doesn't work.
        On some systems, the castle-model-viewer will get an OpenGL context without
        a FrameBuffer (long story short, it means that you cannot capture
        the screen without actually seeing the window) and the resulting screenshot
        will be pure black (or garbage).
        On other systems, there is a problem with `glXChooseVisual`
        that may hang until you actually switch the current terminal
        to the X server.

- The other approach, more reliable in my experience
        (<?php echo a_href_page('please share your own experience
        on the forum', 'forum'); ?>) is to create new X server along with running
        castle-model-viewer, by using `xinit`. See `man xinit` for full
        details, in short use something like `xinit /full/path/to/castle-model-viewer my_model.x3d --screenshot 0 /tmp/output.png -- :1`. The important thing
        is to specify the full path of the castle-model-viewer binary (otherwise xinit
        only adds the arguments to some useless default xterm command-line). Adding `-- :1`
        at the end is only necessary if the default display (`:0`)
        may be already taken. `xinit` will create an X server
        with new display name, run castle-model-viewer, and exit immediately
        when castle-model-viewer exits (which should be as soon as a screenshot is done).
////

=== Other options

--hide-menu::
Hide the top menubar. Useful for full-screen presentations.

--anti-alias AMOUNT::
Use full-screen anti-aliasing. You can also configure it from the menu _"File -> Preferences -> Anti aliasing"_. Using this command-line option is mainly useful together with`--screenshot` option.
+
Argument `AMOUNT` is an integer >= 0. Value `0` means "no anti-aliasing", this is the default. Larger integer values (maximum is 4) make the result look better.
+
There is no guarantee what specific values of `AMOUNT` exactly mean, as this depends on your graphic card capabilities. Just test each method and decide which looks best on your system and is fast enough.

--viewpoint VIEWPOINT-NAME::
Specify the name or a number of the viewpoint that will be bound (used) when the scene is loaded.
+
By default, when this option is not used, we follow X3D standard and use the first viewpoint found in the file (but not in the inlined files).
//Of course you can always add nodes to the scene to trigger binding other viewpoints at the beginning (for example, add `ProximitySensor` with very large size that sends the `enter` event to the `set_bind` of chosen viewpoint). Or you can just exchange the order of viewpoint nodes. But sometimes it's not comfortable to edit the scene. Especially if you want to use the `--screenshot` options to capture a scene, it's useful to be able to choose a viewpoint by this command-line option.
+
When the given `VIEWPOINT-NAME` is a number, it is treated as the index of viewpoint to be used (0 means the first viewpoint, 1 means the 2nd viewpoint and so on). Otherwise, `VIEWPOINT-NAME` is treated as a node name (node name is given by `"DEF Xxx"` in X3D, and it cannot start with a digit, so this is unambiguous).
+
In interactive mode, remember that you don't need this option -- instead you can use comfortable _"Navigation -> Jump To Viewpoint"_ menu.

--no-x3d-extensions::
Do not use Castle Game Engine extensions to X3D.
+
For example we will not use `Tangent`, `flipVertically`,`gravityTransform` when importing glTF to X3D. This affects both rendering and converting to X3D using _"File -> Save As..."_ menu item. This makes X3D output valid in all X3D browsers, albeit a little less functional.

== Converting model formats

In GUI mode, you can use menu items _"File -> Save As..."_ to save (converting if needed) model to a new format.

- Most formats (*glTF 2.0, Collada, Spine JSON, 3DS, MD3, Wavefront OBJ, GEO, sprite sheets*) are always converted *to X3D*.

- Formats *Inventor, VRML 1.0, VRML 2.0, X3D* can be saved back *to their original format*.
+
In this case, castle-model-viewer is simply a "pretty-printer", exactly preserving all the information inside the file, only reformatting your content and removing the comments.

- *VRML 2.0* can be also converted *to X3D*.
+
Conversion from VRML 2.0 to X3D is mostly trivial. There are some different keywords between VRML 2 and X3D, but generally X3D is simply a superset of everything that VRML 2 has.

You can also change the X3D encoding (from classic to XML or the other way around). Changing encoding is a lossless operation, as the same nodes graph can be exactly expressed in both encodings.

All these conversions can be also performed in batch mode using link:castle-model-converter[] command-line tool.

WARNING: We used to also support `--write-xxx` options for `castle-model-viewer`. They are deprecated now. Use link:castle-model-converter[] to do command-line conversion. It is more functional, and the command-line is also simpler.

[#ffmpeg]
== Recording and playing movies using ffmpeg

To play movies (in X3D `MovieTexture` nodes) and to record movies (by `--screenshot-range` option) you have to install http://ffmpeg.mplayerhq.hu/[ffmpeg]
and make sure it's available on $PATH.

Linux and FreeBSD::
Install `ffmpeg` package using your distribution package manager.

Windows::
- Find `ffmpeg` downloads on http://ffmpeg.mplayerhq.hu/[ffmpeg] site.
- Or use https://community.chocolatey.org/[Chocolatey] and install https://community.chocolatey.org/packages/ffmpeg[ffmpeg] by running `choco install ffmpeg`.

_macOS_::
Install `ffmpeg` using various macOS package managers like:
+
--
- https://brew.sh/[HomeBrew]
- https://www.macports.org/[MacPorts]
- http://www.finkproject.org/[Fink]
--

Supported movie formats and extensions:

- video/x-msvideo (.avi)
- video/mpeg (.mpeg, .mpg, .mpe)
- video/ogg (.ogv)
- video/quicktime (.mov)
- video/x-flv (.flv)
- application/x-shockwave-flash (.swf, .swfl)
- video/mp4 (.mp4)
