Movatterモバイル変換


[0]ホーム

URL:


Version:1.3.31
Title:3D Visualization Using OpenGL
Depends:R (≥ 3.6.0)
Suggests:MASS, rmarkdown (≥ 2.16), deldir (≥ 1.0-4), orientlib,lattice, misc3d, magick, plotrix (≥ 3.7-3), interp,alphashape3d, tcltk, js (≥ 1.2), webshot2 (≥ 0.1.0), downlit(≥ 0.4.0), pkgdown (≥ 2.0.0), extrafont, shiny,manipulateWidget (≥ 0.9.0), testthat, crosstalk, V8, chromote,jpeg, png, markdown, xdvir, grid
Imports:graphics, grDevices, stats, utils, htmlwidgets (≥ 1.6.0),htmltools, knitr (≥ 1.33), jsonlite (≥ 0.9.20), magrittr, R6,base64enc, mime
Enhances:waldo
Description:Provides medium to high level functions for 3D interactive graphics, including functions modelled on base graphics (plot3d(), etc.) as well as functions for constructing representations of geometric objects (cube3d(), etc.). Output may be on screen using OpenGL, or to various standard 3D file formats including WebGL, PLY, OBJ, STL as well as 2D image formats, including PNG, Postscript, SVG, PGF.
License:GPL-2 |GPL-3 [expanded from: GPL]
URL:https://github.com/dmurdoch/rgl,https://dmurdoch.github.io/rgl/
SystemRequirements:OpenGL and GLU Library (Required for display in R.See "Installing OpenGL support" in README.md. Not needed ifonly browser displays using rglwidget() are wanted.), zlib(optional), libpng (>=1.2.9, optional), FreeType (optional),pandoc (>=1.14, needed for vignettes), LaTeX needed foroptional latex3d() examples.
BugReports:https://github.com/dmurdoch/rgl/issues
VignetteBuilder:knitr, rmarkdown
Biarch:true
RoxygenNote:7.3.3
NeedsCompilation:yes
Packaged:2025-11-13 18:37:55 UTC; murdoch
Author:Duncan Murdoch [aut, cre], Daniel Adler [aut], Oleg Nenadic [ctb], Simon Urbanek [ctb], Ming Chen [ctb], Albrecht Gebhardt [ctb], Ben Bolker [ctb], Gabor Csardi [ctb], Adam Strzelecki [ctb], Alexander Senger [ctb], The R Core Team [ctb, cph], Dirk Eddelbuettel [ctb], The authors of Shiny [cph], The authors of knitr [cph], Jeroen Ooms [ctb], Yohann Demont [ctb], Joshua Ulrich [ctb], Xavier Fernandez i Marin [ctb], George Helffrich [ctb], Ivan Krylov [ctb], Michael Sumner [ctb], Mike Stein [ctb], Jonathon Love [ctb], Mapbox team [ctb, cph]
Maintainer:Duncan Murdoch <murdoch.duncan@gmail.com>
Repository:CRAN
Date/Publication:2025-11-14 08:40:02 UTC

3D visualization device system

Description

3D real-time rendering system.

Details

RGL is a 3D real-time rendering system for R.Multiple windows are managed at a time. Windowsmay be divided into “subscenes”, where one has the current focusthat receives instructions from the R command-line. The device design is oriented towards the R device metaphor. If you sendscene management instructions, and there's no device open, it will be openedautomatically.Opened devices automatically get the current device focus. The focus may bechanged by usingset3d() oruseSubscene3d().

RGL provides medium to high level functions for 3D interactive graphics, includingfunctions modelled on base graphics (plot3d(), etc.) as well as functions for constructing geometric objects (cube3d(), etc.). Outputmay be on screen using OpenGL, or to various standard 3D file formats including WebGL, PLY, OBJ, STL as well as 2D image formats, including PNG, Postscript, SVG, PGF.

Theopen3d() function attempts to open a new RGL window,using default settings specified by the user.

See the first example below to display the ChangeLog.

See Also

r3d for a description of the*3d interface;par3d for a description of scene properties and the renderingpipeline;rgl.useNULL for a description of how to use RGL on a system with no graphics support.

Examples

if (!in_pkgdown_example())  file.show(system.file("NEWS", package = "rgl"))example(surface3d)example(plot3d)

Check for an open RGL window.

Description

Mostly for internal use, this function returns the current devicenumber if one exists, or opens a new device and returns that.

Usage

.check3d()

Value

The device number of an RGL device.

Author(s)

Duncan Murdoch

See Also

open3d

Examples

rgl.dev.list().check3d()rgl.dev.list().check3d()rgl.dev.list()close3d()

R6 Class for binary buffers in glTF files.

Description

These files typically have one buffer holding all thebinary data for a scene.

Methods

Public methods


Methodnew()

Usage
Buffer$new(json = NULL, binfile = NULL)
Arguments
json

list read from glTF file.

binfile

optional External binary filename, or raw vector


Methodload()

Load from file.

Usage
Buffer$load(uri, buf = 0)
Arguments
uri

Which file to load.

buf

Which buffer number to load.


MethodsaveOpenBuffer()

Write open buffer to connection.

Usage
Buffer$saveOpenBuffer(con, buf = 0)
Arguments
con

Output connection.

buf

Buffer number.


MethodgetBuffer()

Get buffer object.

Usage
Buffer$getBuffer(buf, default = list(byteLength = 0))
Arguments
buf

Buffer number.

default

Default buffer object ifbuf not found.

Returns

A list containing components described here:https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-buffer.


MethodsetBuffer()

Set buffer object.

Usage
Buffer$setBuffer(buf, buffer)
Arguments
buf

Buffer number.

buffer

New value to insert.


MethodopenBuffer()

Open a connection for the data in a buffer.

Usage
Buffer$openBuffer(buf)
Arguments
buf

Buffer number.

Returns

An open binary connection.


MethodwriteBuffer()

Write data to buffer.

Usage
Buffer$writeBuffer(values, type, size, buf = 0)
Arguments
values

Values to write.

type

Type to write.

size

Byte size of each value.

buf

Which buffer to write to.

Returns

Byte offset of start of bytes written.


MethodcloseBuffer()

Close the connection in a buffer.

If there was a connection open, this will save thecontents in the raw vectorbytes within the buffer object.

Usage
Buffer$closeBuffer(buf)
Arguments
buf

The buffer number.


MethodcloseBuffers()

Close any open buffers.

Call this after working with a GLTF file to avoid warningsfrom R about closing unused connections.

Usage
Buffer$closeBuffers()

MethodgetBufferview()

GetbufferView object.

Usage
Buffer$getBufferview(bufv)
Arguments
bufv

bufferView number.

Returns

A list containing components described here:https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-bufferview.


MethodaddBufferView()

Add a new buffer view.

Usage
Buffer$addBufferView(values, type, size, target = NULL, buf = 0)
Arguments
values

Values to put in the view.

type

Type of values.

size

Size of values in bytes.

target

Optional target use for values.

buf

Which buffer to write to.

Returns

NewbufferView number.


MethodopenBufferview()

Open a connection to a buffer view.

Usage
Buffer$openBufferview(bufv)
Arguments
bufv

WhichbufferView.

Returns

A connection.


MethodsetBufferview()

SetbufferView object.

Usage
Buffer$setBufferview(bufv, bufferView)
Arguments
bufv

bufferView number.

bufferView

New value to insert.


MethodgetAccessor()

Get accessor object

Usage
Buffer$getAccessor(acc)
Arguments
acc

Accessor number

Returns

A list containing components described here:https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-accessor


MethodsetAccessor()

Set accessor object.

Usage
Buffer$setAccessor(acc, accessor)
Arguments
acc

Accessor number.

accessor

New value to insert.


MethodreadAccessor()

Read data given by accessor number.

Usage
Buffer$readAccessor(acc)
Arguments
acc

Accessor number.

Returns

A vector or array as specified in the accessor. For theMATn types, the 3rd indexindexes the element.


MethodreadAccessor0()

Read data given by accessor object.

Usage
Buffer$readAccessor0(accessor)
Arguments
accessor

Accessor object

Returns

A vector or array as specified in the accessor. For theMATn types, the 3rd indexindexes the element.


MethodaddAccessor()

Write values to accessor, not includingmin andmax.

Usage
Buffer$addAccessor(  values,  target = NULL,  types = "anyGLTF",  normalized = FALSE)
Arguments
values

Values to write.

target

Optional target use for values.

types

Which types can be used?

normalized

Are normalized integers allowed?

useDouble

Whether to write doubles or singles.

Returns

New accessor number


MethoddataURI()

Convert buffer to data URI.

Usage
Buffer$dataURI(buf = 0)
Arguments
buf

Buffer to convert.

Returns

String containing data URI.


Methodas.list()

Convert to list.

Usage
Buffer$as.list()
Returns

List suitable for writing using JSON.


Methodclone()

The objects of this class are cloneable with this method.

Usage
Buffer$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


The Gram-Schmidt algorithm

Description

Generate a 3x3 orthogonal matrix using the Gram-Schmidt algorithm.

Usage

GramSchmidt(v1, v2, v3, order = 1:3)

Arguments

v1,v2,v3

Three length 3 vectors (taken as row vectors).

order

The precedence order for the vectors; see Details.

Details

This function orthogonalizes the matrixrbind(v1, v2, v3)using the Gram-Schmidt algorithm. It can handle rank 2 matrices(returning a rank 3 matrix). If the original is rank 1, it is likelyto fail.

Theorder vector determines the precedence of the originalvectors. For example, if it isc(i, j, k), then rowi will be unchanged (other than normalization); rowj willnormally be transformed within the span of rowsi andj. Rowk will be transformed orthogonally to the span ofthe others.

Value

A 3x3 matrix whose rows are the orthogonalization of the originalrow vectors.

Author(s)

Duncan Murdoch

Examples

# Proceed through the rows in orderprint(A <- matrix(rnorm(9), 3, 3))GramSchmidt(A[1, ], A[2, ], A[3, ])# Keep the middle row unchangedprint(A <- matrix(c(rnorm(2), 0, 1, 0, 0, rnorm(3)), 3, 3, byrow = TRUE))GramSchmidt(A[1, ], A[2, ], A[3, ], order = c(2, 1, 3))

Lines intersecting the bounding box

Description

This adds mathematical lines to a scene. Their intersection with the currentbounding box will be drawn.

Usage

abclines3d(x, y = NULL, z = NULL, a, b = NULL, c = NULL, ...)

Arguments

x,y,z

Coordinates of points through which each line passes.

a,b,c

Coordinates of the direction vectors for the lines.

...

Material properties.

Details

Draws the segment of a line that intersects the currentbounding box of the scene using the parametrization (x, y, z) + (a, b, c) * s wheres is a real number.

Any reasonable way of defining thecoordinatesx, y, z anda, b, c is acceptable. See the functionxyz.coordsfor details.

Value

A shape ID of the object is returned invisibly.

See Also

planes3d for mathematical planes.

segments3d draws sections of lines thatdo not adapt to the bounding box.

Examples

plot3d(rnorm(100), rnorm(100), rnorm(100))abclines3d(0, 0, 0, a = diag(3), col = "gray")

Add normal vectors to objects so they render more smoothly

Description

This generic function adds normals at each of the verticesof a polyhedron by averaging the normals of each incident face. This has theeffect of making the surface of the object appear smooth rather than facetedwhen rendered.

Usage

addNormals(x, ...)## S3 method for class 'mesh3d'addNormals(x, angleWeighted = TRUE, ...)

Arguments

x

An object to which to add normals.

...

Additional parameters which will be passed to the methods.

angleWeighted

See Details below.

Details

Currently methods are supplied for"mesh3d" and"shapelist3d" classes.

These methods work by averaging the normals on the faces incident at each vertex. By default these are weighted according to the angle in the polygon at that vertex.IfangleWeighted = FALSE, a slightly fasterbut less accurate weighting by the triangle area is used.

Prior torgl version 0.104.12 an incorrect weighting was used; it can be partially reproduced by usingangleWeighted = NA, but not all the bugs in that scheme will be kept.

Value

A new object of the same class asx, with normals added.

Author(s)

Duncan Murdoch

Examples

open3d()y <- subdivision3d(tetrahedron3d(col = "red"), depth = 3)shade3d(y) # No normalsy <- addNormals(y)shade3d(translate3d(y, x = 1, y = 0, z = 0)) # With normals

Set attributes of vertices based on their age

Description

This is a function to produce actions in response toaplaywidget or Shiny input control. Themental model is that each of the vertices of some object hasa certain birth time; a control sets the current time, so thatvertices have ages depending on the control setting.Attributes of those vertices can then be changed.

Usage

ageControl(births, ages, objids = tagged3d(tags), tags, value = 0,           colors = NULL, alpha = NULL, radii = NULL, vertices = NULL,           normals = NULL, origins = NULL, texcoords = NULL,           x = NULL, y = NULL, z = NULL,           red = NULL, green = NULL, blue = NULL)

Arguments

births

Numeric birth times of vertices.

ages

Chosen ages at which the following attributeswill apply.

objids

Object ids to which the changes apply.

tags

Alternate way to specifyobjids. Ignored ifobjids isgiven.

value

Initial value; typically overridden by input.

colors,alpha,radii,vertices,normals,origins,texcoords

Attributes of the vertices that can be changed. There should beone entry or row for each entry inages.

x,y,z,red,green,blue

These one-dimensionalcomponents of vertices and colors are provided for convenience.

Details

All attributes must have the same number of entries (rows for the matrices)as the ages vector. The births vector must have the same number of entries asthe number of vertices in the object.

Not all objects contain all attributes; if one is chosen that isnot a property of the corresponding object, a Javascriptalert() will begenerated. (This restriction may be removed in the future by attemptingto add the attribute when it makes sense.)

If abirths entry isNA, no change will be made to thatvertex.

Value

A list of class"rglControl" of cleaned up parametervalues, to be used in an RGL widget.

Author(s)

Duncan Murdoch

See Also

TheUser Interaction in WebGL vignettegives more details.

Examples

  saveopts <- options(rgl.useNULL = TRUE)  theta <- seq(0, 4*pi, length.out = 100)  xyz <- cbind(sin(theta), cos(theta), sin(theta/2))  lineid <- plot3d(xyz, type="l", alpha = 0, lwd = 5, col = "blue")["data"]  widget <- rglwidget() %>%  playwidget(ageControl(births = theta,                        ages = c(-4*pi, -4*pi, 1-4*pi, 0, 0, 1),                        objids = lineid,                        alpha = c(0, 1, 0, 0, 1, 0)),             start = 0, stop = 4*pi,             step = 0.1, rate = 4)  if (interactive() || in_pkgdown_example())    widget  options(saveopts)

Compare mesh3d objects in a meaningful way.

Description

These functions allow comparison of mesh3d objects, ignoringirrelevant differences.

compare_proxy.mesh3d can function as acompare_proxy method for thewaldo package, by stripping outNULL componentsand ordering other components alphabetically by name.

all.equal.mesh3d compares mesh3d objects by usingcompare_proxy.mesh3d to standardize them, thenusing the regularall.equal function tocompare them.

Usage

## S3 method for class 'mesh3d'all.equal(target, current, ...)compare_proxy.mesh3d(x, path = "x")

Arguments

target,current

Two mesh3d objects to compare.

x

A single mesh3d object to standardize.

path

The string to use in awaldo display of this object.

...

Additional parameters to pass toall.equal.

Value

all.equal.mesh3d returnsTRUE, or a charactervector describing (some of) the differences.

compare_proxy.mesh3d returns a list containing twocomponents:

object

a copy ofx withrelevant components in alphabetical order.

path

a modification of the path label forx

Note

waldo is not an installation requirement forrglandrgl will never cause it to be loaded.Thecompare_proxy.mesh3d function will only be registered as a method forwaldo::compare_proxyif you loadwaldo beforergl, as would normally happen during testing usingtestthat, or if you loadit before callingmesh3d,as might happen if you are doing manual tests.


Draw arcs

Description

Given starting and ending points on a sphere and the center of thesphere, draw thegreat circle arc between the starting and ending points. Ifthe starting and ending points have different radii, a segment of alogarithmic spiral will join them, unless they are in the samedirection, in which case a straight line will join them.

Usage

arc3d(from, to, center, radius, n, circle = 50, base = 0,plot = TRUE, ...)

Arguments

from

One or more points from which to start arcs.

to

One or more destination points.

center

One or more center points.

radius

If not missing, a vector of lengthn giving theradii at each point betweenfrom andto.If missing, the starting and ending points will be joined bya logarithmic spiral.

n

If not missing, how many segments to use between the first and last point. If missing, a value will be calculated based on theangle between starting and ending points as seen from the center.

circle

How many segments would be used if the arc went completely arounda circle.

base

See Details below.

plot

Should the arcs be plotted, or returned as a matrix?

...

Additional parameters to pass topoints3d.

Details

If any offrom,to orcenter is an n by 3matrix with n > 1, multiple arcs will be drawn by recyclingeach of these parameters to the number of rows of the longestone.

If the vector lengths offrom - center andto - center differ, then instead of a sphericalarc, the function will draw a segment of a logarithmic spiral joiningthe two points.

By default, the arc is drawn along the shortest great circle path fromfrom toto, but thebase parameter can be used to modify this. Ifbase = 1 is used, the longer arc will be followed.Larger positive integer values will result inbase - 1loops in that direction completely around the sphere. Negative values will draw the curve in the same directionas the shortest arc, but withabs(base) full loops.It doesn't make much sense to ask for such loops unlessthe radii offrom andto differ, becausespherical arcs would overlap.Normally thebase parameter is left at its defaultvalue of0.

Whenbase is non-zero, the curve will be constructed in multiplepieces, betweenfrom,to,-from and-to,for as many steps as necessary. Ifn is specified, itwill apply to each of these pieces.

Value

Ifplot = TRUE, called mainly for the side effect of drawing arcs. Invisiblyreturns the object ID of the collection of arcs.

Ifplot = FALSE, returns a 3 column matrix containingthe points that would be drawn as the arcs.

Author(s)

Duncan Murdoch

Examples

normalize <- function(v) v/sqrt(sum(v^2))# These vectors all have the same lengthfrom <- t(apply(matrix(rnorm(9), ncol = 3), 1, normalize))to <- normalize(rnorm(3))center <- c(0, 0, 0)open3d()spheres3d(center, radius = 1, col = "white", alpha = 0.2)arc3d(from, to, center, col = "red")arc3d(from, 2*to, center, col = "blue")text3d(rbind(from, to, center, 2*to),        texts = c(paste0("from", 1:3), "to", "center", "2*to"),       depth_mask = FALSE, depth_test = "always")

Draw an arrow

Description

Draws various types of arrows in a scene.

Usage

arrow3d(p0 = c(1, 1, 1), p1 = c(0, 0, 0),         barblen, s = 1/3, theta = pi/12,         type = c("extrusion", "lines", "flat", "rotation"),         n = 3, width = 1/3, thickness = 0.618 * width,         spriteOrigin = NULL,         plot = TRUE, ...)

Arguments

p0

The base of the arrow.

p1

The head of the arrow.

barblen

The length of the barbs (in display coordinates).Default given bys.

s

The length of the barbs as a fraction of line length. Ignored ifbarblen is present.

theta

Opening angle of barbs

type

Type of arrow to draw. Choose one from the listof defaults. Can be abbreviated. See below.

n

Number of barbs.

width

Width of shaft as fraction of barb width.

thickness

Thickness of shaft as fraction of barb width.

spriteOrigin

If arrow is to be replicated as sprites, the origins relativeto which the sprites are drawn.

plot

IfTRUE (the default), plot the object;otherwise return the computed data thatwould be used to plot it.

...

Material properties passed topolygon3d,shade3d orsegments3d.

Details

Four types of arrows can be drawn. The shapesof all of them are affected byp0,p1,barblen,s,theta, material propertiesin..., andspriteOrigin. Other parameters only affect some of the types, as shown.

"extrusion"

(default) A 3-dimensionalflat arrow, drawn withshade3d. Affected bywidth,thickness andsmooth.

"lines"

Drawn with lines, similar toarrows, drawn withsegments3d. Affected byn.

"flat"

A flat arrow, drawn withpolygon3d. Affected bywidth andsmooth.

"rotation"

A solid of rotation, drawn withshade3d. Affected byn andwidth.

Normally this function draws just one arrow fromp0 top1, butifspriteOrigin is given (in any formthatxyz.coords(spriteOrigin) canhandle), arrows will be drawn for each pointspecified, withp0 andp1 interpreted relative to those origins. Thearrows will be drawn as 3D sprites which willmaintain their orientation as the scene is rotated, so this is a good way to indicateparticular locations of interest in the scene.

Value

Ifplot = TRUE (the default), this iscalled mainly for the side effect of drawingthe arrow; invisibly returns the id(s) of the objects drawn.

Ifplot = FALSE, the data that would beused in the plot (not including materialproperties) is returned.

Author(s)

Design based onheplots::arrow3d, which contains modifications by Michael Friendlyto a function posted by Barry Rowlingson to R-help on 1/10/2010. Additions by Duncan Murdoch.

Examples

xyz <- matrix(rnorm(300), ncol = 3)plot3d(xyz)arrow3d(xyz[1,], xyz[2,], type = "extrusion", col = "red")arrow3d(xyz[3,], xyz[4,], type = "flat",      col = "blue")arrow3d(xyz[5,], xyz[6,], type = "rotation",  col = "green")arrow3d(xyz[7,], xyz[8,], type = "lines",     col = "black")arrow3d(spriteOrigin = xyz[9:12,],            col = "purple")

Convert object to mesh object

Description

Theas.mesh3d generic function converts various objectstomesh3d objects.

The default method takes takes a matrix of vertices as input and (optionally) merges repeated vertices, producing amesh3dobject as output. It will contain either triangles or quads or segments or pointsaccording to thetype argument.

If the generic is called without any argument, it will passall RGL ids from the current scene to theas.mesh3d.rglId method.

Usage

as.mesh3d(x, ...)## Default S3 method:as.mesh3d(x, y = NULL, z = NULL,              type = c("triangles", "quads", "segments", "points"),             smooth = FALSE,              tolerance = sqrt(.Machine$double.eps),              notEqual = NULL,              merge = TRUE,             ...,             triangles)

Arguments

x,y,z

For the generic,x is the object to convert.For the default method,x,y andz arecoordinates. Any reasonable way of defining the coordinates isacceptable. See the functionxyz.coords for details.

type

What type of things should be in the mesh? Triesthis list in order until it finds one that works.

smooth

IfTRUE,addNormals will be called on the meshobject to make it render smoothly.

tolerance

The numerical tolerance to be used inall.equal todetermine whether two vertices should be merged.

notEqual

If notNULL, an n by n matrix of logical values, where n is thenumber of vertices as input.TRUE entries indicate that thecorresponding pair of vertices should not be merged even if they appear equal.

merge

Should apparently equal vertices be merged?

...

Material properties to pass totmesh3d orqmesh3d.

triangles

Deprecated. If present,TRUE indicatestype = "triangles" andFALSE indicatestype = "quads".

Details

The motivation for this function is the following problem: I wasasked whether RGL could render a surface made up of triangles or quadrilaterals to look smooth. It can do that, but needs normals at each vertex; they should be the average of the normals for each polygon sharing that vertex. Then OpenGL will interpolate the normals across the polygons and give the illusion of smoothness.

To do this, it needs to know which polygons share each vertex. If the surface is described as a list of triangles or quadrilaterals, that means identifying vertices that are in multiple polygons, and converting the representation to a"mesh3d" object (which is a matrix of vertices and a matrix of vertex numbers making up triangles or quads). Then theaddNormals function will add the normals.

Sometimes two polygons will share vertices (within numerical tolerance) without the user wanting them to be considered internal to the surface, or might want one sharp edge in an otherwise smooth surface. This means I needed a way to declare that two vertices from the original list of vertices in the triangles or quads are "not equal", even when they test numerically equal. That's what thenotEqual matrix specifies.

Value

A"mesh3d" object with the same faces as in the input, but (ifmerge=TRUE) with vertices that test equal towithintolerance merged.

Author(s)

Duncan Murdoch

Examples

xyz <- matrix(c(-1, -1, -1,                -1,  1, -1,                 1,  1, -1,                 1, -1, -1,                -1,  1, -1,                -1,  1,  1,                 1,  1,  1,                 1,  1, -1,                 1, -1, -1,                 1,  1, -1,                 1,  1,  1,                 1, -1,  1), byrow = TRUE, ncol = 3)mesh <- as.mesh3d(xyz, type = "quads", col = "red")mesh$vbmesh$ibopen3d()shade3d(mesh)# Stop vertices 2 and 5 from being mergednotEQ <- matrix(FALSE, 12, 12)notEQ[2, 5] <- TRUEmesh <- as.mesh3d(xyz, type = "quads", notEqual = notEQ)mesh$vbmesh$ib

Convert alpha-shape surface of a cloud of points toRGL mesh object

Description

Thealphashape3d::ashape3dfunction computes the3D\alpha-shape of a cloud of points. This is an approximationto the visual outline of the cloud. It may include isolatedpoints, line segments, and triangular faces: this functionconverts the triangular faces to an RGLtmesh3d object.

Usage

## S3 method for class 'ashape3d'as.mesh3d(x,                    alpha = x$alpha[1],                    tri_to_keep = 2L,                   col = "gray",                    smooth = FALSE, normals = NULL,                   texcoords = NULL, ...)

Arguments

x

An object of class"ashape3d".

alpha

Whichalpha value stored inx should be converted?

tri_to_keep

Which triangles to keep. Expert use only: seetriangentry inValue section ofashape3dfor details.

col

The surface colour.

smooth

Whether to attempt to add normals to make the surfacelook smooth. See the Details below.

normals,texcoords

Normals and texture coordinates at each vertex can be specified.

...

Additional arguments to pass to use asmaterial3d properties on the resulting mesh.

Details

Edelsbrunner and Mucke's (1994)\alpha-shape algorithm is intended to compute a surface of a general cloud of points.Unlike the convex hull, the cloud may have voids, isolated points, and other oddities. This function is designed to work in the case where the surface is made up of simple polygons.

Ifsmooth = TRUE, this method attempts to orient allof the triangles in the surface consistently and add normalsat each vertex by averaging the triangle normals. However, for some point clouds, the\alpha-shape will contain sheets of polygons with a few solid polyhedra embedded.This does not allow a consistent definition of "inside"and outside. If this is detected, a warning is issuedand the resulting mesh will likely contain boundarieswhere the assumed orientation of triangles changes, resultingin ugly dark lines through the shape. Larger valuesofalpha in the call toalphashape3d::ashape3d may help.

Methods forplot3d andpersp3dare also defined: they call theas.mesh3d method and then plot the result.

Value

A"mesh3d" object, suitable for plotting.

Author(s)

Duncan Murdoch

References

Edelsbrunner, H., Mucke, E. P. (1994). Three-Dimensional Alpha Shapes. ACM Transactions on Graphics, 13(1), pp.43-72.

Lafarge, T. and Pateiro-Lopez, B. (2017).alphashape3d: Implementation of the 3D Alpha-Shapefor the Reconstruction of 3D Sets from a Point Cloud.R package version 1.3.

Examples

if (requireNamespace("alphashape3d", quietly = TRUE)) {  set.seed(123)  n <- 400    # 1000 gives a nicer result, but takes longer  xyz <- rbind(cbind(runif(n), runif(n), runif(n)),               cbind(runif(n/8, 1, 1.5),                      runif(n/8, 0.25, 0.75),                      runif(n/8, 0.25, 0.75)))  ash <- suppressMessages(alphashape3d::ashape3d(xyz, alpha = 0.2))  m <- as.mesh3d(ash, smooth = TRUE)  open3d()  mfrow3d(1, 2, sharedMouse = TRUE)  plot3d(xyz, size = 1)  plot3d(m, col = "red", alpha = 0.5)  points3d(xyz, size = 1)}

Convert object in plot to RGL mesh object

Description

This method attempts to read the attributes of objects in thergl display and construct a mesh3d object to approximate them.

Usage

## S3 method for class 'rglId'as.mesh3d(x, type = NA, subscene = NA, ...)

Arguments

x

A vector of RGL identifiers of objects in the specified subscene.

type

A vector of names of types of shapes to convert. Other shapes will be ignored.

subscene

Which subscene to look in; the defaultNA specifies the current subscene.

...

Ignored.

Details

This function attempts to construct a triangle mesh to approximate one or more objects from the current display. It can handle objects of types fromc("points", "lines", "linestrip", "triangles", "quads", "planes", "surface").

Since this method only produces meshes containing points,segments and triangles, they won't necessarilybe an exact match to the original object.

If the genericas.mesh3d is called with noxargument, this method will be called withx set to the ids in the current scene.

Value

A mesh object.

Author(s)

Duncan Murdoch

See Also

as.triangles3d.rglId for extracting the triangles,clipMesh3d to apply complex clipping to a mesh object.

Examples

# volcano example taken from "persp"#data(volcano)z <- 2 * volcano        # Exaggerate the reliefx <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)zlim <- range(y)zlen <- zlim[2] - zlim[1] + 1colorlut <- terrain.colors(zlen) # height color lookup tablecol <- colorlut[ z - zlim[1] + 1 ] # assign colors to heights for each pointopen3d(useNULL = TRUE)surface3d(x, y, z, color = col)m <- as.mesh3d()close3d()open3d()shade3d(m)

Convert an object to anrglscene object.

Description

This is a placeholder generic function, to allow otherpackages to create"rglscene" objects compatible withthe objects produced byscene3d.

No methods are currently defined inrgl.

Usage

as.rglscene(x, ...)

Arguments

x

Object to convert.

...

Other parameters to pass to methods.


Convert object to a triangular mesh

Description

Converts the quads in a mesh version of an object totriangles by splitting them up. Optionally drops anypoint or segment components.

Usage

as.tmesh3d(x, ...)## Default S3 method:as.tmesh3d(x, drop = FALSE, ...)## S3 method for class 'mesh3d'as.tmesh3d(x, drop = FALSE, keepTags = FALSE, ...)

Arguments

x

An object from which to create a triangular mesh object.

drop

IfTRUE, drop any point or segment components.

keepTags

Whether to include the"tags" component in the output.

...

Ignored in themesh3d method, passed toas.mesh3d in the default method.

Details

The default method simply callsas.mesh3d(x, ...)and passes the result to the"mesh3d" method.

Value

A"mesh3d" object containing no quads. Ifdrop = TRUE, it will only contain triangles.

IfkeepTags = TRUE, a"tags" element will be added to the result. For details, see theclipMesh3dhelp page.

Note

Older versions ofrgl had a"tmesh3d" classfor meshes of triangles. That class is no longer used:as.tmesh3d andtmesh3d both produce"mesh3d" objects.

Author(s)

Duncan Murdoch

See Also

as.triangles3d to get just the coordinates.

Examples

x <- cuboctahedron3d()x             # has quads and trianglesas.tmesh3d(x) # has only triangles

Convert an object to triangles

Description

This generic and its methods extract or creates a matrix of coordinatesof triangles from an object, suitable for passing totriangles3d.

Usage

as.triangles3d(obj, ...)## S3 method for class 'rglId'as.triangles3d(obj,               attribute = c("vertices", "normals", "texcoords", "colors"),               subscene = NA,               ...)

Arguments

obj

The object to convert.

attribute

Which attribute of an RGL object to extract?

subscene

Which subscene is this object in?

...

Additional arguments used by the methods.

Details

The method for"rglId" objects can extract several differentattributes, organizing them as it would organize the vertices forthe triangles.

Value

Ann x 3 matrix containing the vertices of triangles makingup the object. Each successive 3 rows of the matrix corresponds toa triangle.

If the attribute doesn't exist,NULL will be returned.

Author(s)

Duncan Murdoch

See Also

as.mesh3d to also capture material properties.

Examples

open3d()x <- surface3d(x = 1:10, y = 1:10, z = rnorm(100), col = "red")tri <- as.triangles3d(x)open3d()triangles3d(tri, col = "blue")

Convenience functions for RGL HTML layouts

Description

TheasRow function arranges objects in a row in the display;thegetWidgetId function extracts the HTML element IDfrom an HTML widget.

Usage

asRow(..., last = NA, height = NULL, colsize = 1)getWidgetId(widget)

Arguments

...

Either a single"combineWidgets" object produced byasRow or a%>% pipe of RGL objects, or several objects intended for rearrangement.

last

If notNA, the number of objects from... thatare to be arranged in a row. Earlier ones will remain in a column.

height

An optional height for the resulting row. This is normally specifiedin pixels, but will be rescaled as necessary to fit the display.

colsize

A vector of relative widths for the columns in the row.

widget

A single HTML widget from which to extract the HTML element ID.

Details

UsingasRow requires that themanipulateWidgetpackage is installed.

asRow produces a"combineWidgets" object whichis a single column whose last element is another"combineWidgets" object which is a single row.

Ifn objects are given as input andlast is given a valueless thann, the firstn - last objects will be displayedin a column above the row containing thelast objects.

Value

asRow returns a single"combineWidgets" object suitable for display or nestingwithin a more complicated display.

getWidgetId returns a character string containing the HTML element ID of the widget.

Author(s)

Duncan Murdoch

See Also

pipe for the%>% operator. TheUser Interaction in WebGL vignettegives more details.

Examples

if (requireNamespace("manipulateWidget", quietly = TRUE) &&    require("crosstalk", quietly = TRUE)) {  sd <- SharedData$new(mtcars)  ids <- plot3d(sd$origData(), col = mtcars$cyl, type = "s")  # Copy the key and group from existing shared data  rglsd <- rglShared(ids["data"], key = sd$key(), group = sd$groupName())  w <- rglwidget(shared = rglsd) %>%       asRow("Mouse mode: ", rglMouse(getWidgetId(.)),              "Subset: ", filter_checkbox("cylinderselector",                "Cylinders", sd, ~ cyl, inline = TRUE),             last = 4, colsize = c(1,2,1,2), height = 60)  if (interactive() || in_pkgdown_example())    w}

Set the aspect ratios of the current plot

Description

This function sets the apparent ratios of the x, y, and z axesof the current bounding box.

Usage

aspect3d(x, y = NULL, z = NULL)

Arguments

x

The ratio for the x axis, or all three ratios, or"iso"

y

The ratio for the y axis

z

The ratio for the z axis

Details

If the ratios are all 1, the bounding box will be displayed as a cube approximately filling the display.Values may be set larger or smaller as desired. Aspect"iso" signifies that thecoordinates should all be displayed at the same scale, i.e. the bounding box should not berescaled. (This corresponds to the default display beforeaspect3d has been called.)Partial matches to"iso" are allowed.

aspect3d works by modifyingpar3d("scale").

Value

The previous value of the scale is returned invisibly.

Author(s)

Duncan Murdoch

See Also

plot3d,par3d

Examples

  x <- rnorm(100)  y <- rnorm(100)*2  z <- rnorm(100)*3    open3d()  plot3d(x, y, z)  aspect3d(1, 1, 0.5)  highlevel()  # To trigger display  open3d()  plot3d(x, y, z)  aspect3d("iso")  highlevel()

Draw boxes, axes and other text outside the data

Description

These functions draw axes, boxes and text outside the range of the data.axes3d,box3d andtitle3d are the higher level functions; normally the others need not be called directly by users.

Usage

axes3d(edges = "bbox", labels = TRUE, tick = TRUE, nticks = 5, box = FALSE, expand = 1.03, ...)box3d(...) title3d(main = NULL, sub = NULL, xlab = NULL, ylab = NULL, zlab = NULL, line = NA, level = NA, floating = NULL, ...) axis3d(edge, at = NULL, labels = TRUE, tick = TRUE, line = 0, pos = NULL, nticks = 5, ...) mtext3d(text, edge, at = NULL, line = 0, level = 0,         floating = FALSE, pos = NA, ...)

Arguments

edges

a code to describe which edge(s) of the box to use; see Details below

labels

whether to label the axes, or (foraxis3d) thelabels to use

tick

whether to use tick marks

nticks

suggested number of ticks

box

draw the full box if"bbox" axes are used

expand

how much to expand the box around the data

main

the main title for the plot

sub

the subtitle for the plot

xlab,ylab,zlab

the axis labels for the plot

line,level

the "line" of the plot margin to draw the label on, and "level" above or below it

floating

which mode of axis labels? One ofTRUE,FALSE orNA. (NULLmay also be used intitle3d calls).See Details for how these are handled.

edge,pos

the position at which to draw the axis or text

text

the text to draw

at

the value of a coordinate at which to draw the axis or labels.

...

additional parameters which are passed tobbox3d ormaterial3d

Details

The rectangular prism holding the 3D plot has 12 edges. They are identifiedusing 3 character strings. The first character (‘x’, ‘y’, or ‘z’) selects the direction of the axis. The next two characters are each ‘-’ or ‘+’,selecting the lower or upper end of one of the other coordinates. If onlyone or two characters are given, the remaining characters normally default to ‘-’ (but withmtext3d(..., floating = TRUE) the default is ‘+’; see below). For exampleedge = 'x+' draws an x-axis at the high level of y and thelow level of z.

By default,axes3d uses thebbox3d function to draw the axes. The labels will move so that they do not obscure the data. Alternatively,a vector of arguments as described above may be used, in which casefixed axes are drawn usingaxis3d.

As ofrgl version 0.106.21, axis drawing has changedsignificantly. Text drawn in the margins willadapt to the margins (seebbox3d). Theedge andfloating parameters will be recordedin themargin andfloating materialproperties for the object.

Iffloating = FALSE, they will be drawn on thespecified edge.

Iffloating = TRUE, they willmove as the axis labels move when the scene is rotated.The signs on the edge specification are interpreted asagreeing with the axis ticks ‘+’ or disagreeing ‘-’.For example,"x++" will draw text on the x axisin the same edge as the ticks, while"x--" will drawon the opposite edge.

The final possible value forfloating inmtext3d isNA, which reproduces legacyrglbehaviour. Inthis case the labels are not tied to the bounding box,so they should be drawn last, or they could appear insidethe box, overlapping the data.

Intitle3dfloating = NULL (the default) indicates the main title and subtitle will be fixed while the axis labels will befloating. The default locations for title and subtitleareline = 2 andlevel = 2 on edges"x++" and"x--"respectively. The axis labels float atline = 4 andlevel = 1 on the same edge as the ticks.

Theat parameter inaxis3d is the locationof the ticks, defaulting topretty locations.Inmtext3d theat parameter is the locationon the specified axisat which to draw the text, defaulting to the middle of thebounding box.

Theline parameter is the line counting outfrom the box in the same direction as the axis ticks,andlevel is the line out in the orthogonaldirection. The ticks run fromline = 0 toline = 1, and thetick labels are drawn atline = 2. Both are drawn at level 0.

Thepos parameter is only supported in legacy mode. If it is a numeric vector of length 3,edge determinesthe direction of the axis and the tick marks, and the values of theother two coordinates inpos determine the position. Thelevel parameter is ignored in legacy mode.

Formtext3d infloating = TRUE orfloating = FALSE mode,there are 3 special values for theat parameter: it maybe-Inf,NA or+Inf, referring to the bottom, middle or top of the given axis respectively.

Value

These functions are called for their side effects. They return the object IDs ofobjects added to the scene.

Note

mtext3d is a wrapper fortext3dthat sets themargin andfloating materialproperties. In fact, these properties can be set for manykinds of objects (most kinds where it would make sense), with the effect that the object will be drawnin the margin, withx coordinate corresponding toat,y corresponding toline, andzcorresponding tolevel.

Author(s)

Duncan Murdoch

See Also

Classic graphics functionsaxis,box,title,mtext are related.See RGL functionsbbox3d for drawing the box around the plot, andsetAxisCallbacks for customized axes.

Examples

  open3d()  points3d(rnorm(10), rnorm(10), rnorm(10))  # First add standard axes  axes3d()    # and one in the middle (the NA will be ignored, a number would   # do as well)  axis3d('x', pos = c(NA, 0, 0))  # add titles  title3d('main', 'sub', 'xlab', 'ylab', 'zlab')    # Use a log scale for z      open3d()    x <- rnorm(10)  y <- rnorm(10)  z <- exp(rnorm(10, mean = 3, sd = 2))    logz <- log10(z)  zticks <- axisTicks(range(logz), log = TRUE)  zat <- log10(zticks)    plot3d(x, y, logz, zlab = "z")  axes3d(zat = zat, zlab = zticks, box = TRUE)

Set up bounding box decoration

Description

Set up the bounding box decoration.

Usage

bbox3d(xat = NULL, yat = NULL, zat = NULL, xunit = "pretty", yunit = "pretty", zunit = "pretty", expand = 1.03,draw_front = FALSE, xlab=NULL, ylab=NULL, zlab=NULL,  xlen=5, ylen=5, zlen=5,  marklen=15.0, marklen.rel=TRUE, ...)

Arguments

xat,yat,zat

vector specifying the tickmark positions

xlab,ylab,zlab

character vector specifying the tickmark labeling

xunit,yunit,zunit

value specifying the tick mark base for uniform tick mark layout

xlen,ylen,zlen

value specifying the number of tickmarks

marklen

value specifying the length of the tickmarks

marklen.rel

logical, if TRUE tick mark length is calculated using 1/marklen * axis length, otherwise tick mark length ismarklen in coordinate space

expand

value specifying how much to expand the bounding box around the data

draw_front

draw the front faces of the bounding box

...

Material properties (or otherrgl.bbox parametersin the case ofbbox3d). Seematerial3d for details.

Details

Four different types of tick mark layouts are possible.This description applies to the X axis; other axes are similar:Ifxat is notNULL, the ticks are set up at custom positions.Ifxunit is numeric but not zero, it defines the tick mark base. Ifit is"pretty" (the default inbbox3d), ticks are set atprettylocations.Ifxlen is not zero, it specifies the number of ticks(a suggestion ifxunit is"pretty").

The first color specifies the bounding box, while the second one specifies the tick mark and font color.

bbox3d defaults topretty locations for the axis labels and a slightly largerbox, whereasrgl.bbox covers the exact range.

axes3d offers more flexibility in the specification of the axes, but they are static, unlike those drawn bybbox3d.

Value

This function is called for the side effect of setting the bounding box decoration.A shape ID is returned to allowpop3d to delete it.

See Also

material3d,axes3d

Examples

  open3d()  points3d(rnorm(100), rnorm(100), rnorm(100))  bbox3d(color = c("#333377", "black"), emission = "#333377",          specular = "#3333FF", shininess = 5, alpha = 0.8)

Set up background

Description

Set up the background of the scene.

Usage

bg3d(color,    sphere=FALSE,     back="lines",    fogtype="none",    fogScale = 1,     col, ...)

Arguments

color,col

See Details below.

sphere

logical: ifTRUE, an environmental sphere geometry is used for the background decoration.

back

Specifies the fill style of the sphere geometry. Seematerial3d for details.

fogtype

fog type:

"none"

no fog

"linear"

linear fog function

"exp"

exponential fog function

"exp2"

squared exponential fog function

Fog only applies to objects withmaterial3d propertyfog set toTRUE.

fogScale

Scaling for fog. See Details.

...

Additional material properties. Seematerial3d for details.

Details

The background color is taken fromcolor orcolifcolor is missing.The first entryis used for background clearing and as the fog color.The second (if present) is used for background sphere geometry.

Ifcolor andcol are both missing, the default is found in ther3dDefaults$bg list, or"white" is usedif nothing is specified there.

Ifsphere is set toTRUE, an environmentalsphere enclosing the whole scene is drawn.

If not, but the material properties include a bitmap as a texture, the bitmap is drawn in the background of the scene. (The bitmap colors modify the general color setting.)

If neither a sphere nor a bitmap background is drawn, the background is filled with a solid color.

ThefogScale parameter should be a positive valueto change the density of the fog in the plot. Forfogtype = "linear" it multiplies the density of thefog; for the exponential fog types it multiplies the densityparameter used in the display.

Seethe OpenGL 2.1 reference for the formulas used in the fog calculations withinR (though the"exp2" formula appears to be wrong, at least on mysystem). In WebGL displays,the following rules are used. They appear to match therules used inR on my system.

See Also

material3d,bgplot3d to add a 2D plot as background.

Examples

  open3d()    # a simple white background    bg3d("white")  # the holo-globe (inspired by star trek):  bg3d(sphere = TRUE, color = c("black", "green"), lit = FALSE, back = "lines" )  # an environmental sphere with a nice texture.  bg3d(sphere = TRUE, texture = system.file("textures/sunsleep.png", package = "rgl"),          back = "filled" )           # The same texture as a fixed background    open3d()  bg3d(texture = system.file("textures/sunsleep.png", package = "rgl"), col = "white")

Use base graphics for RGL background

Description

Add a 2D plot or a legend in the background of an RGL window.

Usage

bgplot3d(expression, bg.color = getr3dDefaults("bg", "color"),          magnify = 1, ...)legend3d(...)

Arguments

expression

Any plotting commands to produce a plot.

bg.color

The color to use for the background.

magnify

Multiplicative factor to apply to size of window when producing background plot.

...

Forlegend3d, arguments to pass tobgplot3dorlegend; forbgplot3d, arguments to pass tobg3d.

Details

Thebgplot3d function opens apng device and executesexpression,producing a plot there. This plot is then used as a bitmap background for the currentRGL subscene.

Thelegend3d function draws a standard 2D legend to the background of the currentsubscene by callingbgplot3d to open a device, and setting up a plot region there to fill the whole display.

Value

Thebgplot3d function invisibly returns the ID of the background object that was created,with attribute"value" holding the value returned when theexpression wasevaluated.

Thelegend3d function does similarly. The"value" attribute is the resultof the call tolegend. The scaling of the coordinates runs from 0 to 1 in X and Y.

Note

Because the background plots are drawn as bitmaps, they do not resize very gracefully.It's best to size your window first, then draw the background at that size.

Author(s)

Duncan Murdoch

See Also

bg3d for other background options.

Examples

x <- rnorm(100)y <- rnorm(100)z <- rnorm(100)open3d()# Needs to be a bigger window than the defaultpar3d(windowRect = c(100, 100, 612, 612))parent <- currentSubscene3d()mfrow3d(2, 2)plot3d(x, y, z)next3d(reuse = FALSE)bgplot3d(plot(y, z))next3d(reuse = FALSE)bgplot3d(plot(x, z))next3d(reuse = FALSE)legend3d("center", c("2D Points", "3D Points"), pch = c(1, 16))useSubscene3d(parent)

User callbacks on mouse events

Description

Set and get user callbacks on mouse events.

Usage

rgl.setMouseCallbacks(button, begin = NULL, update = NULL, end = NULL,                       dev = cur3d(), subscene = currentSubscene3d(dev))rgl.getMouseCallbacks(button,                       dev = cur3d(), subscene = currentSubscene3d(dev))rgl.setWheelCallback(rotate,                       dev = cur3d(), subscene = currentSubscene3d(dev))rgl.getWheelCallback(dev = cur3d(), subscene = currentSubscene3d(dev))

Arguments

button

Which button? Use 1 for left, 2 forright, 3 for middle, 4 for wheel. Use 0 to setan action when no button is pressed.

begin

Called when mouse down event occurs

update

Called when mouse moves

end

Called when mouse is released

rotate

Called when mouse wheel is rotated

dev,subscene

The RGL device and subscene to work with

Details

The set functions set event handlers on mouse events that occur within the current RGL window.Thebegin andupdate events should be functions taking two arguments; thesewill be the mouse coordinates when the event occurs. Theend event handlertakes no arguments. Therotate event takes a single argument, which will be equal to1 if the user pushes the wheel away by one click, and2 if the user pulls the wheel by one click.

Alternatively, the handlers may be set toNULL, the default value, in which caseno action will occur.

If a subscene has multiple listeners, the user action will still only be called for thesubscene that received the mouse event. It should consultpar3d("listeners")if it makes sense to take action on the whole group of subscenes.

The get function retrieves the callbacks that are currently set.

The “no button” mouse handler may be set byspecifyingbutton = 0. Thebeginfunction will be called the first time the mousemoves within the subscene, and theupdatefunction will be called repeatedly as it moves. Theend function will never be called.

Value

The set functions are called for the side effect of setting the mouse event handlers.

Thergl.getMouseCallbacks function returns a list containing the callback functions orNULL if no user callback is set.Thergl.getWheelCallback returns the callback function orNULL.

Author(s)

Duncan Murdoch

See Also

par3d to set built-in handlers,setUserCallbacks to work withrglwidget.

Examples

 pan3d <- function(button, dev = cur3d(), subscene = currentSubscene3d(dev)) {   start <- list()      begin <- function(x, y) {     activeSubscene <- par3d("activeSubscene", dev = dev)     start$listeners <<- par3d("listeners", dev = dev, subscene = activeSubscene)     for (sub in start$listeners) {       init <- par3d(c("userProjection","viewport"), dev = dev, subscene = sub)       init$pos <- c(x/init$viewport[3], 1 - y/init$viewport[4], 0.5)       start[[as.character(sub)]] <<- init     }   }      update <- function(x, y) {     for (sub in start$listeners) {       init <- start[[as.character(sub)]]       xlat <- 2*(c(x/init$viewport[3], 1 - y/init$viewport[4], 0.5) - init$pos)       mouseMatrix <- translationMatrix(xlat[1], xlat[2], xlat[3])       par3d(userProjection = mouseMatrix %*% init$userProjection, dev = dev, subscene = sub )      }   }   rgl.setMouseCallbacks(button, begin, update, dev = dev, subscene = subscene)   cat("Callbacks set on button", button, "of RGL device", dev, "in subscene", subscene, "\n") } open3d() shade3d(icosahedron3d(), col = "yellow") # This only works in the internal display... pan3d(1)

Check for a compatible version ofdeldir

Description

Version 1.0-2 ofdeldir is not compatible withrgl.This allows code to avoid trying to call it.

Usage

checkDeldir(error = FALSE)

Arguments

error

IfTRUE, stop with an error.

Value

ReturnsTRUE ifdeldir is available in a compatibleversion.

Examples

checkDeldir()

Clip mesh or RGL object to general region

Description

Modifies a mesh3d object so that values of a function are bounded.

Usage

clipMesh3d(mesh, fn, bound = 0, greater = TRUE,            minVertices = 0, plot = FALSE, keepValues = FALSE,           keepTags = FALSE)clipObj3d(ids = tagged3d(tags), fn, bound = 0, greater = TRUE,           minVertices = 0,           replace = TRUE, tags)

Arguments

mesh

Amesh3d object.

fn

A function used to determine clipping, or a vector of values from sucha function, with one value per vertex.

bound

The value(s) offn on the clipping boundary.

greater

Logical; whether to keepfn >= bound or not.

minVertices

See Details below.

plot

Logical; whether or not to plot the mesh.

keepValues

Logical; whether to save the function values at each vertex whenplot = FALSE.

keepTags

Whether to keep the"tags" componentof the result; see details below.

ids

The RGL id value(s) of objects to clip.

tags

Object tags; an alternate way to specifyids. Ignored ifids isgiven.

replace

Should theids objects be deleted after the clippedones are drawn?

Details

These functions transform a mesh3d object or otherRGL objects by removing parts wherefn violatesthe bound.

ForclipMesh3d thefn argument can be anyof the following:

ForclipObj3d any of the above exceptNULLmay be used.

Iffnis a numeric vector, with one value per vertex, those values will beused in the test.If it is a function with formal argumentsx,y andz, it will receive the coordinates of vertices in those arguments, otherwise it will receive the coordinates in a single n x 3 matrix. The functionshould be vectorized and return one value per vertex, to check against the bound.

These operations are performed on the mesh:

First, all quads are converted to triangles.

Next, each vertex is checked against the condition.

Modifications to triangles dependon how many of the vertices satisfy the condition (fn >= bound orfn <= bound, depending ongreater)for inclusion.

Modifications to line segments are similar: the segmentwill be shortened if it crosses the boundary, or omittedif it is entirely out of bounds. Points, spheres, textand sprites will just be kept or rejected.

TheminVertices argument is used to improve the approximation to the boundary whenfn is a non-linearfunction. In that case, the interpolation described abovecan be inaccurate. IfminVertices is set to apositivenumber (e.g.10000), then each object is modifiedby subdivision to have at least that number of vertices, so that pieces are smaller and the linear interpolationis more accurate. In theclipObj3d function,minVertices can be a vector, with entries correspondingto each of the entries inids.

Value

Ifplot = FALSE,clipMesh3d returns new mesh3d object in which all vertices (approximately) satisfy theclipping condition. Note that the order of vertices will likelydiffer from the original order, and new vertices will be added nearthe boundary (and ifminVertices > 0, in the interior). If in additionkeepValues = TRUE,a component named"values" will be added to the mesh containing the values for each vertex.IfkeepTags = TRUE, thetags componentdescribed below will be added to the output mesh.

Ifplot = TRUE, the result will be plotted withshade3d and its result returned.

clipObj3d is called for the side effect of modifyingthe scene. It returns a list of new RGL id valuescorresponding to theids passed as arguments.

ThekeepTags argument

IfkeepTags = TRUE, a"tags" element will be added to the result. It will be a vector with one entry perpoint, segment, triangle and quad in the output mesh. (These tags are not relatedto the tags used to identifyrgl objects.)The mesh tags may be used to show the correspondence betweenthe parts of the input mesh and output mesh.By default, the tags are constructed as a numerical sequenceover points,segments, triangles andquads in the input mesh, in that order, starting from one. This is the same order used for colours when shading withmeshColor == "faces".

For example, start with a mesh with one point, two segments, threetriangles and fourquads, but notags member. It would implicitly tag the parts from one to ten as

⁠ c(1, # the point 2:3, # the two segments 4:6, # the three triangles 7:10) # the four quads⁠

If clipping deleted the segmentsand the first triangle, the output would contain the sevenelement result

⁠ mesh$tags <- c(1, # the point remains # no segments now 5:6, # the two remaining triangles # were previously items 5 and 6 7:10) # the four quads⁠

Thetags output may contain repetitions. For example,when a triangle is partially clipped and replaced by severalsmaller triangles, entries for all of them will contain the valuecorresponding to the original triangle.

Themesh$tags component may be supplied as part of the inputmesh as any type of vector; the output will propagate values to the new mesh. The input lengthmust match the total number of points, segments, triangles and quads in the input mesh or an error will be raised.

Author(s)

Duncan Murdoch

References

Seehttps://stackoverflow.com/q/56242470/2554330 andhttps://laustep.github.io/stlahblog/posts/MeshClipping.html for amotivating example.

See Also

SeecontourLines3d andfilledContour3d for ways to display function values without clipping.

Examples

# Show the problem that minVertices solves:cube <- cube3d(col = rainbow(6), meshColor = "faces")# This function only has one argument, so it will # be passed x, y and z in columns of a matrixvecnorm <- function(vals) apply(vals, 1, function(row) sqrt(sum(row^2)))open3d()mfrow3d(2, 2, sharedMouse = TRUE)id1 <- shade3d(cube)# All vertices have norm sqrt(3), so this clips nothing:clipObj3d(id1, fn = vecnorm, bound = sqrt(2))next3d()id2 <- wire3d(cube, lit = FALSE)clipObj3d(id2, fn = vecnorm, bound = sqrt(2))# This subdivides the cube, and does proper clipping:next3d()id3 <- shade3d(cube)clipObj3d(id3, fn = vecnorm, bound = sqrt(2), minVertices = 200)next3d()id4 <- wire3d(cube, lit = FALSE)clipObj3d(id4, fn = vecnorm, bound = sqrt(2), minVertices = 200)

Sets attributes of a clipping plane

Description

This is a function to produce actions in a web display. Aplaywidget or Shinyinput control (e.g. asliderInput control)sets a value which controls attributes of one or more clippingplanes.

Usage

clipplaneControl(a = NULL, b = NULL, c = NULL, d = NULL,                  plane = 1, clipplaneids = tagged3d(tag), tag, ...)

Arguments

a,b,c,d

Parameter values for the clipping planes.

plane

Which plane in the clipplane object?

clipplaneids

The id of the clipplane object.

tag

Select clipplane with matching tag. Ignoredifclipplaneid is specified.

...

Other parameters passed topropertyControl.

Value

A list of class"rglControl" of cleaned up parametervalues, to be used in an RGL widget.

Author(s)

Duncan Murdoch

See Also

TheUser Interaction in WebGL vignettegives more details.

Examples

  open3d()  saveopts <- options(rgl.useNULL = TRUE)  xyz <- matrix(rnorm(300), ncol = 3)  id <- plot3d(xyz, type="s", col = "blue", zlim = c(-3,3))["clipplanes"]  dvals <- c(3, -3)  widget <- rglwidget() %>%    playwidget(clipplaneControl(d = dvals, clipplaneids = id),               start = 0, stop = 1, step = 0.01,               rate = 0.5)  if (interactive() || in_pkgdown_example())    widget  options(saveopts)

Draw contours on a surface

Description

contourLines3d draws contour lines on a surface;filledContour3d draws filled contours on it.

Usage

contourLines3d(obj, ...)## S3 method for class 'rglId'contourLines3d(obj, ...)## S3 method for class 'mesh3d'contourLines3d(obj, fn = "z",     nlevels = 10,     levels = NULL,     minVertices = 0,    plot = TRUE, ... )filledContour3d(obj, ...)## S3 method for class 'rglId'filledContour3d(obj, plot = TRUE, replace = plot, ...)## S3 method for class 'mesh3d'filledContour3d(obj, fn = "z",     nlevels = 20,     levels = pretty(range(values), nlevels),     color.palette = function(n) hcl.colors(n, "YlOrRd", rev = TRUE),    col = color.palette(length(levels) - 1),    minVertices = 0,    plot = TRUE,     keepValues = FALSE, ... )

Arguments

obj

The object(s) on which to draw contour lines.

fn

The function(s) to be contoured. See Details.

nlevels

Suggested number of contour levels iflevels is not given.

levels

Specified contour values.

minVertices

See Details below.

plot

Whether to draw the lines or return them in a dataframe.

...

For the"mesh3d" methods, additional parameters to pass tosegments3dwhen drawing the contour lines or toshade3dwhen drawing the filled contours. For the"rglId"methods, additional parameters to pass to the"mesh3d"methods.

replace

Whether to delete the objects that are being contoured.

color.palette

a color palette function to assign colors in the plot

col

the actual colors to use in the plot.

keepValues

whether to save the function values at each vertex whenplot = FALSE

Details

ForcontourLines3d, thefn argument can be anyof the following:

ForfilledContour3d, only one function can be specified.

The special names"x", "y", "z" may be used infn to specify functions returning one of thosecoordinates. (If you have existing functionsx(),y()orz() they will be masked by this choice; specifysuch functions by value rather than name, e.g.fn = xinstead offn = "x".)

Functions infn with formal argumentsx,y andz will receive the coordinates of vertices in those arguments, otherwise they will receive the coordinates in a single n x 3 matrix. They shouldbe vectorized and return one value per vertex.

Each of the functions will be evaluated at each vertexof the surface specified byobj, and contours willbe drawn assuming the function is linear between vertices.If contours of a nonlinear function are needed, you maywant to increaseminVertices as described below.

Iflevels is not specified, values will be setseparately for each entry infn, usingpretty(range(values, na.rm = TRUE), nlevels) wherevalues are the values on the vertices.

TheminVertices argument is used to improve the approximation to the contour when the function is non-linear.In that case, the interpolation between vertices can be inaccurate. IfminVertices is set to apositivenumber (e.g.10000), then the mesh is modifiedby subdivision to have at least that number of vertices, so that pieces are smaller and the linear interpolationis more accurate.

Value

For bothcontourLines3d andfilledContour3dthe"rglId" method converts the given id values toa mesh, and calls the"mesh3d" method.

The"mesh3d" method returns an object of class"rglId" corresponding to what wasdrawn ifplot isTRUE,

Ifplot isFALSE,contourLines3d returns a dataframe containing columnsc("x", "y", "z", "fn", "level") givingthe coordinates of the endpoints of each line segment, the name (or index) of the function for this contour, and the level of the contour.

Ifplot isFALSE,filledContour3dreturns a"mesh3d" object holding the result.IfkeepValues isTRUE, the meshwill contain the values corresponding to each vertex(with linear approximations at the boundaries).

Note

To draw contours on a surface, the surface should be drawnwith material propertypolygon_offset = 1 (or perhapssome larger positive value) so that the lines of the contour are notobscured by the surface.

In R versions prior to 3.6.0, the defaultcolor.paletteisgrDevices::cm.colors.

Author(s)

Duncan Murdoch

See Also

Themisc3d package contains the functioncontour3dto draw contour surfaces in space instead of contour lineson surfaces.

Examples

# Add contourlines in "z" to a persp plotz <- 2 * volcano        # Exaggerate the reliefx <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)open3d()id <- persp3d(x, y, z, aspect = "iso",      axes = FALSE, box = FALSE, polygon_offset = 1)contourLines3d(id)     # "z" is the default functionfilledContour3d(id, polygon_offset = 1, nlevels = 10, replace = TRUE)# Draw longitude and latitude lines on a globelat <- matrix(seq(90, -90, length.out = 50)*pi/180, 50, 50, byrow = TRUE)long <- matrix(seq(-180, 180, length.out = 50)*pi/180, 50, 50)r <- 6378.1 # radius of Earth in kmx <- r*cos(lat)*cos(long)y <- r*cos(lat)*sin(long)z <- r*sin(lat)open3d()ids <- persp3d(x, y, z, col = "white",         texture = system.file("textures/worldsmall.png", package = "rgl"),         specular = "black", axes = FALSE, box = FALSE, xlab = "", ylab = "", zlab = "",        normal_x = x, normal_y = y, normal_z = z, polygon_offset = 1)        contourLines3d(ids, list(latitude = function(x, y, z) asin(z/sqrt(x^2+y^2+z^2))*180/pi,                         longitude = function(x, y, z) atan2(y, x)*180/pi))

Sample 3D mesh objects

Description

A collection of sample mesh objects.

Usage

  cube3d(trans = identityMatrix(), ...)    tetrahedron3d(trans = identityMatrix(), ...)    octahedron3d(trans = identityMatrix(), ...)    icosahedron3d(trans = identityMatrix(), ...)  dodecahedron3d(trans = identityMatrix(), ...)  cuboctahedron3d(trans = identityMatrix(), ...)    oh3d(trans = identityMatrix(), ...)    # an 'o' object

Arguments

trans

transformation to apply to objects

...

additional parameters to pass tomesh3d

Details

These sample objects optionally take a 4x4 matrix transformationtrans as an argument. This transformation is applied to all vertices of the default shape.The default is an identity transformation.

Value

Objects of classc("mesh3d", "shape3d").

See Also

mesh3d

Examples

  # render all of the Platonic solids  open3d()  shade3d( translate3d( tetrahedron3d(col = "red"), 0, 0, 0) )  shade3d( translate3d( cube3d(col = "green"), 3, 0, 0) )  shade3d( translate3d( octahedron3d(col = "blue"), 6, 0, 0) )  shade3d( translate3d( dodecahedron3d(col = "cyan"), 9, 0, 0) )  shade3d( translate3d( icosahedron3d(col = "magenta"), 12, 0, 0) )

Create cylindrical or "tube" plots

Description

This function converts a description of a space curve into a"mesh3d"object forming a cylindrical tube around the curve.

Usage

cylinder3d(center, radius = 1, twist = 0, e1 = NULL, e2 = NULL, e3 = NULL, sides = 8, section = NULL, closed = 0, rotationMinimizing = is.null(e2) && is.null(e3),debug = FALSE, keepVars = FALSE, ...)

Arguments

center

An n by 3 matrix whose columns are the x, y and z coordinates of the space curve.

radius

The radius of the cross-section of the tube at each point in the center.

twist

The amount by which the polygon forming the tube is twisted at each point.

e1,e2,e3

The local coordinates to use at each point on the space curve. These default to a rotationminimizing frame or Frenet coordinates.

sides

The number of sides in the polygon cross section.

section

The polygon cross section as a two-column matrix, orNULL.

closed

Whether to treat the first and last points of the space curve as identical,and close the curve, or put caps on the ends. See the Details.

rotationMinimizing

Use a rotation minimizing localframe ifTRUE, or a Frenet or user-specified frame ifFALSE.

debug

IfTRUE, plot the local Frenet coordinates at each point.

keepVars

IfTRUE, return the local variables in attribute"vars".

...

Additional arguments to set as material properties.

Details

The number of points in the space curve is determined by the vector lengths incenter,after usingxyz.coords to convert it to a list. The other argumentsradius,twist,e1,e2, ande3 are extended to the samelength.

Theclosed argument controls how the ends of the cylinder arehandled. Ifclosed > 0, it represents the number of points ofoverlap in the coordinates.closed == TRUE is the same asclosed = 1. Ifclosed > 0 but the ends don't actually match, a warning will be given and results will be somewhat unpredictable.

Negative values ofclosed indicate that caps should be put on theends of the cylinder. Ifclosed == -1, a cap will be put on theend corresponding tocenter[1, ]. Ifclosed == -2, capswill be put on both ends.

Ifsection isNULL (the default), a regularsides-sided polygon is used, andradius measures thedistance from the center of the cylinder to each vertex. If notNULL,sides is ignored (and set internally tonrow(section)), andradius is used as a multiplier tothe vertex coordinates.twist specifies the rotation of thepolygon. Bothradius andtwist may be vectors, withvalues recycled to the number of rows incenter, whilesides andsection are the same at every point along thecurve.

The three optional argumentse1,e2, ande3determine the local coordinate system used to create the vertices ateach point incenter. If missing, they are computed by simplenumerical approximations.e1 should be the tangent coordinate,giving the direction of the curve at the point. The cross-section ofthe polygon will be orthogonal toe1. WhenrotationMinimizing isTRUE,e2 ande3 are chosen to givea rotation minimizing frame (see Wang et al., 2008). When it isFALSE,e2 defaults to anapproximation to the normal or curvature vector; it is used as theimage of they axis of the polygon cross-section.e3defaults to an approximation to the binormal vector, to which thex axis of the polygon maps. The vectors are orthogonalized andnormalized at each point.

Value

A"mesh3d" object holding the cylinder, possibly withattribute"vars" containing the local environment of the function.

Author(s)

Duncan Murdoch

References

Wang, W., Jüttler, B., Zheng, D. and Liu, Y. (2008). Computation of rotation minimizing frames. ACM Transactions on Graphics, Vol. 27, No. 1, Article 2.

Examples

# A trefoil knotopen3d()theta <- seq(0, 2*pi, length.out = 25)knot <- cylinder3d(      center = cbind(        sin(theta) + 2*sin(2*theta),         2*sin(3*theta),         cos(theta) - 2*cos(2*theta)),      e1 = cbind(        cos(theta) + 4*cos(2*theta),         6*cos(3*theta),         sin(theta) + 4*sin(2*theta)),      radius = 0.8,       closed = TRUE,      color = "green")                     shade3d(addNormals(subdivision3d(knot, depth = 2)))

Add decorations to a 3D plot

Description

decorate3d adds the usual decorations to a plot: labels, axes, etc.

Usage

decorate3d(xlim = NULL, ylim = NULL, zlim = NULL,            xlab = "x", ylab = "y", zlab = "z",            box = TRUE, axes = TRUE,            main = NULL, sub = NULL,            top = TRUE, aspect = FALSE, expand = 1.03,            tag = material3d("tag"), ...)

Arguments

xlim,ylim,zlim

These are usedfor the labels.

xlab,ylab,zlab

labels for the coordinates.

box,axes

whether to draw a box and axes.

main,sub

main title and subtitle.

top

whether to bring the window to the top when done.

aspect

either a logical indicating whether to adjust the aspect ratio, or a new ratio.

expand

how much to expand the box around the data, if it is drawn.

tag

optional label for objectsbeing produced.

...

ignored.

Value

The RGL id values for those items.

Examples

open3d()shade3d(tetrahedron3d(), col = "red")decorate3d(main = "A Tetrahedron")

Drape lines over a scene.

Description

Project a line onto the surface in a scene so that it appears to drape itselfonto the surface.

Usage

drape3d(obj, ...)## S3 method for class 'mesh3d'drape3d(obj, x, y = NULL, z = NULL, plot = TRUE,                         up = c(0, 0, 1),                         P = projectDown(up), ...)## Default S3 method:drape3d(obj, ...)

Arguments

obj

The object(s) upon which to drape lines.

x,y,z

Coordinates of the line segmentsto be draped. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coords for details.

plot

Should the result be plotted, or returned as a data frame?

up

The direction to consider as “up”.

P

The projection to use for draping, a 4x4 matrix.

...

For the"mesh3d" method, additional parameters to pass tosegments3dwhen drawing the draped lines.For the"default" method, additional parameters to pass to the"mesh3d" method.

Details

The default method convertsobj to a meshusingas.mesh3d, then uses the"mesh3d"method.

The current implementation constructs the segments to drapeacross the surface using the same method aslines3d uses: each successive point isjoined to the previous one. UseNA coordinates toindicate breaks in the line.

TheP matrix is used to project points to a plane asfollows: They are transformed byP in homogeneous coordinates, then only first two (Euclidean)coordinates are kept.

Value

Ifplot = TRUE, plots the result and invisibly returns the object ID of the collection of segments.

Ifplot = FALSE, returns a matrix containing "x", "y" and "z"values for the line(s) (for use withsegments3d),

Author(s)

George Helffrich and Duncan Murdoch

See Also

shadow3d,facing3d

Examples

## volcano example taken from "persp"#z <- 2 * volcano        # Exaggerate the reliefx <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)zlim <- range(z)zlen <- zlim[2] - zlim[1] + 1colorlut <- terrain.colors(zlen) # height color lookup tablecol <- colorlut[ z - zlim[1] + 1 ] # assign colors to heights for each pointopen3d()id <- surface3d(x, y, z, color = col, polygon_offset = 1)segs <- data.frame(x = range(x) + c(100, -100),                   y = range(y) + c(150, -100), z = 325)drape3d(id, segs, col = 'yellow', lwd = 3)lines3d(segs, col='red', lwd=3)p <- c(350, 205)         # (x,y) of strike & dip readingoff <- 20*c(-1, +1)      # X-marks-the-spot offsetsegs <- data.frame(    x = c(p[1] + off, NA, p[1] + off),    y = c(p[2] + off, NA, p[2] - off),    z = rep(350, 5)    )drape3d(id, segs, col = "yellow", lwd = 3)

Use widget with old-style controls

Description

Therglwidget control is designed to work in thehtmlwidgets framework. Older RGL web pages thatused the deprecatedwriteWebGL orknitr used a differentmethod of linking the controls to the scene. This is a partialbridge between the two systems. You should adopt the new system, not use this function.

Usage

elementId2Prefix(elementId, prefix = elementId)

Arguments

elementId

An element identifier from arglwidget call.

prefix

The prefix to use in the old-style control.

Value

This function generates Javascript code, so it should beused in anresults = "asis" block in aknitr document.

Author(s)

Duncan Murdoch


Make an ellipsoid

Description

A generic function and several methodsreturning an ellipsoid or other outline of a confidence regionfor three parameters.

Usage

ellipse3d(x, ...)## Default S3 method:ellipse3d(x, scale = c(1, 1, 1), centre = c(0, 0, 0), level = 0.95, t = sqrt(qchisq(level, 3)), which = 1:3, subdivide = 3, smooth = TRUE, ...)## S3 method for class 'lm'ellipse3d(x, which = 1:3, level = 0.95, t = sqrt(3 * qf(level,                                                 3, x$df.residual)), ...)     ## S3 method for class 'glm'ellipse3d(x, which = 1:3, level = 0.95, t, dispersion, ...) ## S3 method for class 'nls'ellipse3d(x, which = 1:3, level = 0.95, t = sqrt(3 * qf(level,                                                 3, s$df[2])), ...)

Arguments

x

An object. In the default method the parameterx should be a square positive definite matrix at least 3x3in size. It will be treated as the correlation or covariance of a multivariate normal distribution.

...

Additional parameters to pass to the default method or toqmesh3d.

scale

Ifx is a correlation matrix, then the standard deviations of eachparameter can be given in the scale parameter. This defaults toc(1, 1, 1),so no rescaling will be done.

centre

The centre of the ellipse will be at this position.

level

The confidence level of a simultaneous confidence region. The default is0.95, for a 95% region. This is used to control the size of the ellipsoid.

t

The size of the ellipse may also be controlled by specifying the valueof a t-statistic on its boundary. This defaults to the appropriatevalue for the confidence region.

which

This parameter selects which variables from the object will beplotted. The default is the first 3.

subdivide

This controls the number of subdivisions (seesubdivision3d)used in constructing the ellipsoid. Higher numbers give a smoother shape.

smooth

IfTRUE, smooth interpolation of normals is used; ifFALSE, a faceted ellipsoid will be displayed.

dispersion

The value of dispersion to use. If specified, it is treated as fixed,and chi-square limits fort are used. If missing, it is taken fromsummary(x).

Value

Amesh3d object representing the ellipsoid.

Examples

# Plot a random sample and an ellipsoid of concentration corresponding to a 95% # probability region for a# trivariate normal distribution with mean 0, unit variances and # correlation 0.8.if (requireNamespace("MASS", quietly = TRUE)) {  Sigma <- matrix(c(10, 3, 0, 3, 2, 0, 0, 0, 1), 3, 3)  Mean <- 1:3  x <- MASS::mvrnorm(1000, Mean, Sigma)    open3d()    plot3d(x, box = FALSE)    plot3d( ellipse3d(Sigma, centre = Mean), col = "green", alpha = 0.5, add = TRUE)}  # Plot the estimate and joint 90% confidence region for the displacement and cylinder# count linear coefficients in the mtcars datasetdata(mtcars)fit <- lm(mpg ~ disp + cyl , mtcars)open3d()plot3d(ellipse3d(fit, level = 0.90), col = "blue", alpha = 0.5, aspect = TRUE)

Helper fortestthat testing.

Description

Gets the current scene usingscene3d, andcompares the result to a saved value, optionally closingthe window afterwards.

Usage

expect_known_scene(name,                    close = TRUE,                    file = paste0("testdata/", name, ".rds"),                   ...)

Arguments

name

By default, the base name of the file to save results in.Not used iffile is specified.

close

Whether to close thergl window after the comparison.

file

The file in which to save the result.

...

Other arguments which will be passed toexpect_known_value.

Details

This function usesexpect_known_value to save a representation of the scene. During the comparison, the sceneis modified so that non-reproducible aspects are standardizedor omitted:

Calls toexpect_known_scene() enabletestthat::local_edition(2) for the duration of the call, so it will work intestthat “3rd edition”.

Value

A value describing the changes to the saved object,suitable for use intest_that().

Examples

## Not run: # These lines can be included in testthat::test_that() code.plot3d(1:10, 1:10, 1:10)expect_known_scene("plot")## End(Not run)

Generate extrusion mesh

Description

Given a two-dimensional polygon, this generates a three-dimensional extrusionof the shape by triangulating the polygon and creating a cylinder withthat shape as the end faces.

Usage

extrude3d(x, y = NULL, thickness = 1, smooth = FALSE, ...)

Arguments

x,y

A polygon description in one of the forms supported bytriangulate.

thickness

The extrusion will have this thickness.

smooth

logical; should normals be added so that the edges of the extrusion appearsmooth?

...

Other parameters to pass totmesh3d when constructing themesh.

Details

The extrusion is always constructed with the polygon in the xy plane atz = 0 and another copy atz = thickness. Usethe transformation functions (e.g.rotate3d) to obtain other orientations and placements.

Value

A mesh object containing a triangulation of the polygonfor each face, and quadrilaterals for the sides.

Author(s)

Duncan Murdoch

See Also

polygon3d for a simple polygon,triangulate forthe triangulation,turn3d for a solid of rotation.

Examples

x <- c(1:10, 10:1)y <- rev(c(rep(c(0, 2), 5), rep(c(1.5, -0.5), 5)))plot(x, y, type = "n")polygon(x, y)open3d()shade3d( extrude3d(x, y), col = "red" )

Subset an object to parts facing in a particular direction

Description

facing3d subsets an object by converting it to a triangle mesh,then subsetting to those triangles that are counterclockwise(forfront = TRUE) when projected into a plane.

projectDown computes a projection that “looks down” the specified direction.

Usage

facing3d(obj, up = c(0, 0, 1),          P = projectDown(up),          front = TRUE, strict = TRUE)projectDown(up)

Arguments

obj

An object that can be converted to a triangular mesh object.

up

The direction that is to be considered “up”. It maybe either a 3 vector in Euclidean coordinates or a 4 vector inhomogeneous coordinates.

P

The projection to use for draping, a 4x4 matrix. Seedrape3d for details on howP is used.

front

Iffront = TRUE, retains triangles that are counterclockwise after projection byP, otherwiseretains those that are clockwise.

strict

IfTRUE, drops indeterminate triangles(those that are annihilated byP).

Details

By default the returned subset will be those triangles whose upper sidematchesfront. Changeup or use anarbitrary projection for different subsets.

drape3d andshadow3d project objects onto meshes; these functions can be used toproject only onto the top or front.

Value

facing3d returns a mesh object made of those triangles which face in the desired direction.

projectDown computes a 4x4 matrix. The first twocoordinates ofasEuclidean(x %*% projectDown(up)) give a projection ofx from above into a plane, whereup determines which direction is taken to be “up”.

See Also

drape3d,shadow3d

Examples

open3d()d <- rnorm(3)d <- d/sqrt(sum(d^2))shade3d( facing3d( icosahedron3d(), up = d, strict = FALSE),          col = "yellow")wire3d( facing3d( icosahedron3d(), up = d, front = FALSE),          col = "black")# Show the direction:arrow3d(-2*d , -d)

Get R Markdown figure dimensions in pixels

Description

In an R Markdown document, figure dimensions are normallyspecified in inches; these are translated into pixeldimensions when HTML output is requested andrglwidget is used. These functions reproduce thattranslation.

Usage

figWidth()figHeight()

Value

When used in an R Markdown document, these functionsreturn the requested current dimensions of figures in pixels. Outside such a document,NULLis returned.

Author(s)

Duncan Murdoch

Examples

# No useful return value outside of R Markdown:figWidth()figHeight()

Extract the boundary of a mesh

Description

Constructs a mesh of line segments corresponding tonon-shared (i.e. boundary) edges of triangles or quadsin the original mesh.

Usage

getBoundary3d(mesh, sorted = FALSE, simplify = TRUE, ...)

Arguments

mesh

A mesh object.

sorted

Whether the result should have the segments sorted insequential order.

simplify

Whether to simplify the resulting mesh, dropping all unusedvertices. IfFALSE, the vertices of the result will be identical to the vertices ofmesh; ifTRUE,they will likely be different, even if no vertices were dropped.

...

Material properties to apply to the mesh.

Value

A"mesh3d" object containing 0 or more segments.

Author(s)

Duncan Murdoch

See Also

mesh3d

Examples

x <- cube3d(col = "blue")x$ib <- x$ib[,-(1:2)]b <- getBoundary3d(x, sorted = TRUE, col = "black")open3d()shade3d(x, alpha=0.2)shade3d(b) # Show edge vertices in sequence:text3d(t(b$vb), texts = 1:ncol(b$vb), adj = 0)c(b$is[1,1], b$is[2,])

Names of glTF types.

Description

The glTF specification packs data into buffers, labellingthe type of each part with an integer. The first six valuesingltfTypes are theintegers used there, with"int" and"double"added for completeness; those values are taken fromOpenGL header files.

Usage

gltfTypes

Format

gltfTypes is simply a named vector containing integer values.

Details

These are used in theBuffer object.

References

https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#_accessor_componenttype

Examples

gltfTypes

Add a grid to a 3D plot

Description

This function adds a reference grid to an RGL plot.

Usage

grid3d(side, at = NULL, col = "gray", lwd = 1, lty = 1, n = 5)

Arguments

side

Where to put the grid; see the Details section.

at

How to draw the grid; see the Details section.

col

The color of the grid lines.

lwd

The line width of the grid lines. (Currently onlylty = 1 is supported.)

lty

The line type of the grid lines.

n

Suggested number of grid lines; see the Details section.

Details

This function is similar togrid in classic graphics,except that it draws a 3D grid in the plot.

The grid is drawn in a plane perpendicular to the coordinate axes. Thefirst letter of theside argument specifies the direction ofthe plane:"x","y" or"z" (or uppercaseversions) to specify the coordinate which is constant on the plane.

Ifat = NULL (the default), the grid is drawn at the limit of the box around the data. If the second letter of theside argumentis"-" or is not present, it is the lower limit; if"+"then at the upper limit. The grid lines are drawn at valueschosen bypretty withn suggested locations.The default locations should match those chosen byaxis3dwithnticks = n.

Ifat is a numeric vector, the grid lines are drawn at those values.

Ifat is a list, then the"x" component is used tospecify the x location, the"y" component specifies the y location, andthe"z" component specifies the z location. Missing componentsare handled using the default as forat = NULL.

Multiple grids may be drawn by specifying multiple values forsideor for the component ofat that specifies the grid location.

Value

A vector or matrix of object ids is returned invisibly.

Note

If the scene is resized, the grid will not be resized; useabclines3dto draw grid lines that will automatically resize.

Author(s)

Ben Bolker and Duncan Murdoch

See Also

axis3d

Examples

x <- 1:10y <- 1:10z <- matrix(outer(x - 5, y - 5) + rnorm(100), 10, 10)open3d()persp3d(x, y, z, col = "red", alpha = 0.7, aspect = c(1, 1, 0.5))grid3d(c("x", "y+", "z"))

Display hover info in plot.

Description

This adds text to identify points within a plot when the mouse is near them.

Usage

hover3d(x, y = NULL, z = NULL,         labeller = NULL,         tolerance = 20,         persist = c("no", "one", "yes"),         labels = seq_along(x),        adj = c(-0.2, 0.5),        scene = scene3d(minimal = FALSE),        applyToScene = TRUE,        ...)

Arguments

x,y,z

Coordinates of point to identify. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coords for details. Alternatively,x may be the id of a single existing object, and its vertices will be used.

labeller

A function to display information about identified points.NULLindicates the default function, described in Details.

tolerance

How close (in pixels) the mouse should be to a point to display theinformation.

persist

Should the label persist? If"no" (the default), it will be removedwhen the mouse moves away. If"one", it will be removed when another point is closer to the mouse. If"yes", it will not be removed.

labels

If the defaultlabeller is used, these labels will be displayed.

adj

If the defaultlabeller is used, this adjustment will be passedtotext3d to display the labels.

scene,applyToScene

Arguments to pass tosetUserCallbacks.TheapplyToDev argument to that function is alwaysTRUE.

...

Additional arguments that will be passed to the labeller.

Details

If specified, thelabeller argument should specify afunction with argumentscompatible withfunction(index, ...). It will be called withindex being the index of the point that was selected. It shouldplot the label, and return thergl ids of the objects that were plotted.

WhenapplyToScene isTRUE, all labelsor labelling objects will be created and attached to the scene. You may want todelete them (using the ids returned inidverts andidtexts) oncerglwidget has been called,as they serve no purpose in the current device.

Only one hover handler is supported per scene or device.

Value

Alowlevel vector of ids is returned invisibly.IfapplyToScene isTRUE, it will contain theids of the temporary objects created for Javascript.It will also have these attributes:

oldPar

Values ofpar3d parameters that were changed.Currently only"mouseMode".

oldDev

The value ofcur3d() at the time of calling, so thatoldPar can be restored to the right device.

Author(s)

Duncan Murdoch

See Also

identify3d andselectpoints3dwork in thergl device and return informationabout the selections.setUserCallbacksis the underlying function used byhover3d.

Examples

# Create a labeller to show the coordinates of the selected point.labelLocation <- function(x, y = NULL, z = NULL) {  xyz <- xyz.coords(x, y, z)  function(sel, ...) {    p <- with(xyz, matrix(c(x[sel], y[sel], z[sel]), ncol = 3))    c(text3d(p, texts = sprintf("x:%.2f", p[1]),                   adj = c(-0.2, -0.6), ...),      text3d(p, texts = sprintf("y:%.2f", p[2]),                  adj = c(-0.2, 0.5), ...),      text3d(p, texts = sprintf("z:%.2f", p[3]),                  adj = c(-0.2, 1.6), ...))  }}xyz <- matrix(rnorm(30), ncol = 3)open3d()ids <- plot3d(xyz)hover3d(xyz, labeller = labelLocation(xyz), col = "red", cex = 0.8)# The same thing using the data id:# hover3d(ids["data"], #         labeller = labelLocation(rgl.attrib(ids["data"], "vertices")), #         col = "red", cex = 0.8)

Identify points in plot

Description

Identify points in a plot, similarly to theidentify functionin base graphics.

Usage

identify3d(x, y = NULL, z = NULL, labels = seq_along(x), n = length(x), plot = TRUE, adj = c(-0.1, 0.5), tolerance = 20, buttons = c("right", "middle"))

Arguments

x,y,z

coordinates of points in a scatter plot. Alternatively, anyobject which defines coordinates (seexyz.coords) can be given asx, andy andz left missing.

labels

an optional character vector giving labels for thepoints. Will be coerced usingas.character, andrecycled if necessary to the length ofx.

n

the maximum number of points to be identified.

plot

logical: ifplot isTRUE, the labels areprinted near the points and ifFALSE they are omitted.

adj

numeric vector to use asadj parameter totext3d when plotting the labels.

tolerance

the maximal distance (in pixels) for the pointer to be ‘close enough’ to a point.

buttons

a length 1 or 2 character vector giving the buttonsto use for selection and quitting.

Details

Ifbuttons is length 1, the user can quit by reachingnselections, or by hitting the escape key, but the result will be lost if escape is used.

Value

A vector of selected indices.

Author(s)

Duncan Murdoch

See Also

identify for base graphics,select3d for selecting regions.


Imported from magrittr

Description

This object is imported frommagrittr. Follow the link to its documentation.

magrittr

%>%

Pipes can be used to string togetherrglwidget calls andplaywidgetcalls. SeeageControl for an example.


Are we running inpkgdown or apkgdown example?

Description

This is mainly for internal use to decide whether resultsshould be automatically included in apkgdown webpage.

See theUsing RGL in pkgdown web sitesvignette for details about usingpkgdown.

Usage

in_pkgdown()in_pkgdown_example()

Value

TRUE orFALSE

Examples

in_pkgdown_example()

Add light source

Description

add a light source to the scene.

Usage

light3d(theta=0, phi=15,        x=NULL, y = NULL, z = NULL,        viewpoint.rel = TRUE,         ambient = "#FFFFFF",         diffuse = "#FFFFFF",         specular = "#FFFFFF")

Arguments

theta,phi

direction to infinitely distant light

x,y,z

position of finitely distant light

viewpoint.rel

logical, if TRUE light is a viewpoint light that is positioned relative to the current viewpoint

ambient,diffuse,specular

light color values used for lighting calculation

Details

Up to 8 light sources are supported. They are positioned either inworld space or relative to the camera. By providing polarcoordinates totheta andphi a directional light source is used. Ifnumerical values are given to x, y and z, a point-like light source withfinite distance to the objects in the scene is set up.

Ifx is non-null,xyz.coords willbe used to form the location values, so all three coordinatescan be specified inx.

If no lights have been added to a subscene, lights from the parentsubscene will be used.

Seematerial3d for a discussion of howthe components of the light affect the display of objects.

Value

This function is called for the side effect of adding a light. A light ID isreturned to allowpop3d to remove it.

See Also

clear3dpop3d

Examples

## a lightsource moving through the scene#data(volcano)z <- 2 * volcano # Exaggerate the reliefx <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W)zlim <- range(z)zlen <- zlim[2] - zlim[1] + 1colorlut <- terrain.colors(zlen) # height color lookup tablecol <- colorlut[ z - zlim[1] + 1 ] # assign colors to heights for each pointopen3d()bg3d("gray50")surface3d(x, y, z, color = col, back = "lines")r <- max(y) - mean(y)lightid <- spheres3d(1, 1, 1, alpha = 0)frame <- function(time) {    a <- pi*(time - 1)    save <- par3d(skipRedraw = TRUE)    clear3d(type = "lights")    pop3d(id = lightid)    xyz <- matrix(c(r*sin(a) + mean(x), r*cos(a) + mean(y), max(z)), ncol = 3)    light3d(x = xyz, diffuse = "gray75",             specular = "gray75", viewpoint.rel = FALSE)     light3d(diffuse = "gray10", specular = "gray25")    lightid <<- spheres3d(xyz, emission = "white", radius = 4)    par3d(save)    Sys.sleep(0.02)    NULL}play3d(frame, duration = 2)

Process Javascript for HTML dependency

Description

A utility function to help in development of internal Javascript code, this function processes the Javascriptto minify it and report on errors and bad style.

Usage

makeDependency(name, src, script = NULL, package,                version = packageVersion(package),               minifile = paste0(basename(src), ".min.js"),               debugging = FALSE, ...)

Arguments

name,src,script,package,version,...

Arguments to pass tohtmltools::htmlDependency.

minifile

Basename of minified file.

debugging

See details below.

Details

This is a utility function used by RGL to process its Javascript code used when displayingrglwidget values. It may be helpful in other packages to usein their own installation.

If thejs package version 1.2 or greater is installed,the Javascript code will be minified and stored in the file namedbyminifile in thesrc directory. Syntax errorsin the code will stop the process; unused variables will bereported.

Ifdebugging isTRUE, the locations of Javascript syntaxerrors will be reported, along with hints about improvements,and the original files will be used in the dependency objectthat is created.

Ifdebugging isFALSE (the default), the minified file will be used in the dependency object,hints won't be given, and syntax errors will lead to anuninformative failure to minify.

Value

An object that can be included in a list of dependencies passed tohtmltools::attachDependencies.

Note

The usual way to usemakeDependency is to call it in a ‘.R’ file in a package, savingthe result in a variable that will be used when anHTML widget is created. This way it is only runduring package installation, when it is safe towrite to the R library holding the package.

Do not call it to write to the R library from code the user can run, as that is not allowed ingeneral.

If your package uses Roxygen, you may have problemsbecause by default Roxygen will run the code, and itis likely to fail. The current workaround is tospecify Roxygen optionload = "installed"which prevents it from running your ‘.R’ code.

Author(s)

Duncan Murdoch

Examples

## Not run: # This is a slightly simplified version of the code used to # produce one of the dependencies for rglwidget().  # It writes to the system library copy of rgl so # has been marked not to run in the example code.makeDependency("rglwidgetClass",                src = "htmlwidgets/lib/rglClass",               script = c("rglClass.src.js",                          "utils.src.js",                          "buffer.src.js",                          "subscenes.src.js",                          "shaders.src.js",                          "textures.src.js",                          "projection.src.js",                          "mouse.src.js",                          "init.src.js",                          "pieces.src.js",                          "draw.src.js",                          "controls.src.js",                          "selection.src.js",                          "rglTimer.src.js",                          "pretty.src.js",                          "axes.src.js",                          "animation.src.js"),               stylesheet = "rgl.css",               package = "rgl",               debugging = isTRUE(as.logical(Sys.getenv("RGL_DEBUGGING", "FALSE"))))## End(Not run)

Get or set material properties

Description

Get or set material properties for geometry appearance.

Usage

material3d(..., id = NULL)rgl.material.namesrgl.material.readonly

Arguments

...

Material properties to set or query.

id

thergl id of an object to query, orNULLto query or set the defaults.

Details

In anrgl scene, each object has “material properties” that control how it is rendered and (in the case oftag) that can be used to store a label or other information.material3d sets defaultsfor these properties and queries the defaults or specificvalues for an individual object.

To set values, usename = value settings, e.g.material3d(color = "red"). To query values, specify the property or properties in a character vector,e.g.material3d("color").

Only one side at a time can be culled.

Thematerial member of ther3dDefaults list may be used to set default values for material properties.

Value

material3d() returns values similarlytopar3d:When setting properties, it returns the previous valuesinvisibly in a named list. When querying multiple values, anamed list is returned. When a single value is queried it isreturned directly.

Material Properties

Thergl.material.names variable contains thefull list of material names.The following read-write material properties controlthe appearanceof objects in anrgl scene.

color

vector of R color characters. Represents the diffuse component in case of lighting calculation (lit = TRUE),otherwise it describes the solid color characteristics.

lit

logical, specifying if lighting calculation should take place on geometry

ambient, specular, emission, shininess

properties for lighting calculation. ambient, specular, emission are R color character string values; shininess represents anumerical.

alpha

vector of alpha values between 0.0 (fully transparent) and 1.0 (opaque). SeeA Note on Transparency for a discussion of some issues with transparency.

smooth

logical, specifying whether smooth shading or flat shadingshould be used. For smooth shading, Gouraud shading isused inrgl windows, while Phong shading is used in WebGL.

texture

path to a texture image specification. See the Textures sectionbelow for details.

textype

specifies what is defined with the pixmap

"alpha"

alpha values

"luminance"

luminance

"luminance.alpha"

luminance and alpha

"rgb"

color

"rgba"

color and alpha texture

Note that support for these modes is slightly differentin the display within R versus the WebGL display usingrglwidget(). In particular, in WebGLtextype = "alpha" will always take the alpha value fromthe luminance (i.e. the average of the R, G and B channels) of the texture, whereas the R display basesthe choice on the internal format of the texture file.

texmode

specifies how the texture interacts with the existingcolor

"replace"

texture value replaces existing value

"modulate"

default; texture value multiplies existing value

"decal"

fortextype = "rgba", textureis mixed with existing value

"blend"

uses the texture to blend the existingvalue with black

"add"

adds the texture value to the existing.May not be available in the R display with very oldOpenGL drivers.

texmipmap

Logical, specifies if the texture should be mipmapped.

texmagfilter

specifies the magnification filtering type (sorted by ascending quality):

"nearest"

texel nearest to the center of the pixel

"linear"

weighted linear average of a 2x2 array of texels

texminfilter

specifies the minification filtering type (sorted by ascending quality):

"nearest"

texel nearest to the center of the pixel

"linear"

weighted linear average of a 2x2 array of texels

"nearest.mipmap.nearest"

low quality mipmapping

"nearest.mipmap.linear"

medium quality mipmapping

"linear.mipmap.nearest"

medium quality mipmapping

"linear.mipmap.linear"

high quality mipmapping

texenvmap

logical, specifies if auto-generated texture coordinates for environment-mapping should be performed on geometry.

front, back

Determines the polygon mode for the specified side:

"filled"

filled polygon

"lines"

wireframed polygon

"points"

point polygon

"culled"

culled (hidden) polygon

size

numeric, specifying the size of points in pixels

lwd

numeric, specifying the line width in pixels

fog

logical, specifying if fog effect should be applied on the corresponding shape. Fog type is set inbg3d.

point_antialias, line_antialias

logical, specifying if points should be round and lines should be antialiased, but see Note below.

depth_mask

logical, specifying whether the object's depthshould be stored.

depth_test

Determines which depth test is used to see if thisobject is visible, depending on its apparent depth in the scenecompared to the stored depth. Possible values are"never","less" (the default),"equal","lequal"(less than or equal),"greater","notequal","gequal" (greater than or equal),"always".

polygon_offset

A one or two elementvector giving the ‘⁠factor⁠’ and ‘⁠units⁠’ valuesto use in aglPolygonOffset() call in OpenGL. Ifonly one value is given, it is used for both elements.The ‘⁠units⁠’ value is added to the depth of all pixels ina filled polygon,and the ‘⁠factor⁠’ value is multiplied by an estimate ofthe slope of the polygon and then added to the depth. Positive values “push” polygons back slightly for the purposeof depth testing, to allow points, lines or other polygonsto be drawn on the surface without being obscured due to rounding error. Negative values pull the object forward.A typical value to use is1 (whichis automatically expanded toc(1,1)).If values are too large, objects which should be behindthe polygon will show through, and if values are too small,the objects on the surface will be partially obscured. Experimentation may be needed to get it right. The firstexample in?persp3d uses this property to add grid lines to a surface.

margin, floating

Used mainly for text todraw annotations in the margins, but supported bymost kinds of objects: seemtext3d.

tag

A length 1 string value. Thesemay be used to identify objects, or encode other metadata about the object.

blend

Two string values from the list belowdescribing how transparent objects are blended withcolors behind them.The first determines the coefficient applied to the color of the current object (the source); the second determinesthe coefficient applied to the existing color (the destination). The resultingcolor will be the sum of the two resulting colors.The allowed stringscorrespond to OpenGL constants:

"zero"

Zero; color has no effect.

"one"

One; color is added to the other term.

"src_color", "one_minus_src_color"

Multiply by source color or its opposite.

"dst_color", "one_minus_dst_color"

Multiply by destination color or its opposite.

"src_alpha", "one_minus_src_alpha"

Multiply bysource alpha or its opposite. Default values.

"dst_alpha", "one_minus_dst_alpha"

Multiply bydestination alpha or its opposite.

"constant_color", "one_minus_constant_color","constant_alpha", "one_minus_constant_alpha","src_alpha_saturate"

These are allowed, but to be usefulthey require other settings whichrgl doesn'tsupport.

col

An allowed abbreviation ofcolor.

Thergl.material.readonly variable containsthe subset of material properties that are read-onlyso they can be queriedbut not set.Currently there is only one:

isTransparent

Is the current color transparent?

Textures

Thetexture material property may beNULL or the name ofa bitmap file to be displayed on the surface being rendered.Currently PNG and JPEG format files are supported. It mayalso be any other object for whichas.raster() works, e.g. a matrix.

By default, the colors in the bitmap will modify the color of theobject being plotted. If the color is black (a common default), youwon't see anything, so a warning may be issued. You cansuppress the warning by specifying the color explicitly, or callingoptions{rgl.warnBlackTexture = FALSE}.

Other aspects of texture display are controlled by the materialpropertiestextype, texmode, texmipmap, texmagfilter,texminfilter andtexenvmap described above.

For an extensive discussion of textures, see theTextures section of thergl Overviewvignette.

Display of objects

Object display colors are determined as follows:

Ifpoint_antialias isTRUE, points will be drawn as circles in WebGL; otherwise, theywill be drawn as squares. Within R, the behaviour dependson your graphics hardware: for example, I see circles for both settings on my laptop.

Within R, lines tend to appear heavier withline_antialias == TRUE. There's no difference at allin WebGL.

See Also

bbox3d,bg3d,light3d

Examples

save <- material3d("color")material3d(color = "red")material3d("color")material3d(color = save)# this illustrates the effect of depth_testx <- c(1:3); xmid <- mean(x)y <- c(2, 1, 3); ymid <- mean(y)z <- 1open3d()tests <- c("never", "less", "equal", "lequal", "greater",                   "notequal", "gequal", "always")for (i in 1:8) {  triangles3d(x, y, z + i, col = heat.colors(8)[i])  texts3d(xmid, ymid, z + i, paste(i, tests[i], sep = ". "), depth_test = tests[i]) }highlevel()  # To trigger display# this illustrates additive blendingopen3d()bg3d("darkgray")quad <- cbind(c(-1, 1, 1, -1), 1, c(-1, -1, 1, 1))quads3d(rbind(translate3d(quad, -0.5, 0, -0.5),              translate3d(quad, 0.5,  0.5, -0.5),              translate3d(quad, 0, 1, 0.5)),         col = rep(c("red", "green", "blue"), each = 4),        alpha = 0.5,         blend = c("src_alpha", "one"))

Work with homogeneous coordinates

Description

These functions construct 4x4 matrices for transformationsin the homogeneous coordinate system used by OpenGL, and translatevectors between homogeneous and Euclidean coordinates.

Usage

identityMatrix()scaleMatrix(x, y, z)translationMatrix(x, y, z)rotationMatrix(angle, x, y, z, matrix)asHomogeneous(x)asEuclidean(x)asHomogeneous2(x)asEuclidean2(x)scale3d(obj, x, y, z, ...)translate3d(obj, x, y, z, ...)rotate3d(obj, angle, x, y, z, matrix, ...)transform3d(obj, matrix, ...)

Arguments

x,y,z,angle,matrix

See details

obj

An object to be transformed

...

Additional parameters to be passed to methods

Details

OpenGL uses homogeneous coordinates to handle perspective and affinetransformations. The homogeneous point(x, y, z, w) correspondsto the Euclidean point(x/w, y/w, z/w). The matrices produced bythe functionsscaleMatrix,translationMatrix, androtationMatrixare to be left-multiplied by a row vector of homogeneous coordinates; alternatively, the transpose of the resultcan be right-multiplied by a column vector. The generic functionsscale3d,translate3d androtate3d apply these transformationsto theobj argument. Thetransform3d function is a synonym forrotate3d(obj, matrix = matrix).

By default, it is assumed thatobj is a row vector(or a matrix of row vectors) which will be multiplied on the right bythe corresponding matrix, but users may write methods for these genericswhich operate differently. Methods are supplied formesh3dobjects.

To compose transformations, use matrix multiplication. The effect isto apply the matrix on the left first, followed by the one on the right.

identityMatrix returns an identity matrix.

scaleMatrix scales each coordinate by the given factor. In Euclideancoordinates,(u, v, w) is transformed to(x*u, y*v, z*w).

translationMatrix translates each coordinate by the given translation, i.e.(u, v, w) is transformed to(u + x, v + y, w + z).

rotationMatrix can be called in three ways. With argumentsangle, x, y, z it represents a rotation ofangle radians about the axisx, y, z. Ifmatrix is a 3x3 rotation matrix,it will be converted into the corresponding matrix in 4x4 homogeneouscoordinates. Finally, if a 4x4 matrix is given, it will be returned unchanged.(The latter behaviour is used to allowtransform3d to act like a generic function, even though it is not.)

UseasHomogeneous(x) to convert the Euclidean vectorx tohomogeneous coordinates, andasEuclidean(x) for the reverse transformation. These functions accept the followinginputs:

Outputs are n x 4 or n x 3 matrices forasHomogeneousandasEuclidean respectively.

The functionsasHomogeneous2 andasEuclidean2act similarly, but they assume inputs are 3 x n or 4 x nand outputs are in similar shapes.

Value

identityMatrix,scaleMatrix,translationMatrix, androtationMatrix producea 4x4 matrix representing the requested transformationin homogeneous coordinates.

scale3d,translate3d androtate3d transform the objectand produce a new object of the same class.

Author(s)

Duncan Murdoch

See Also

par3d for a description of how RGL uses matrices inrendering.

Examples

# A 90 degree rotation about the x axis:rotationMatrix(pi/2, 1, 0, 0)# Find what happens when you rotate (2, 0, 0) by 45 degrees about the y axis:x <- asHomogeneous(c(2, 0, 0))y <- x %*% rotationMatrix(pi/4, 0, 1, 0)asEuclidean(y)# or more simply...rotate3d(c(2, 0, 0), pi/4, 0, 1, 0)

Merge RGL mesh objects

Description

Attempts to merge"mesh3d" objects. Objects needto be similar enough; see Details.

Usage

## S3 method for class 'mesh3d'merge(x, y, ..., attributesMustMatch = FALSE)

Arguments

x,y

"mesh3d" objects to merge.

...

Optional additional objects.

attributesMustMatch

See Details.

Details

To allow objects to be merged, they need to be similar enoughin terms of having the same list of material properties,normals, texture coordinates, etc.

IfattributesMustMatch isTRUE, it is an errorto have attributes in one mesh but not in another, and those attributes that only specify a single value must have equalvalues in all meshes.

IfattributesMustMatch isFALSE, any non-matchingattributes will be dropped from the final result.

Value

A single"mesh3d" object merging the contentsof the arguments.

Author(s)

Duncan Murdoch

Examples

open3d()# Notice that the alpha setting for the cube is dropped, because# the other shapes don't specify alpha.shade3d(merge(cube3d(col="red", alpha = 0.5),              translate3d(tetrahedron3d(col="green"), 2, 0, 0),              translate3d(octahedron3d(col="blue"), 4, 0, 0)))

Merge duplicate vertices in mesh object

Description

A mesh object can have the same vertex listed twice. Each copy isallowed to have separate normals, texture coordinates, and color.However, it is more efficient to have just a single copy if thosedifferences aren't needed. For automatic smoothing usingaddNormals, triangles and quads need to share vertices.This function merges identical (or similar) vertices to achieve this.

Usage

mergeVertices(mesh,               notEqual = NULL,               attribute = "vertices",               tolerance = sqrt(.Machine$double.eps))

Arguments

mesh

Amesh3d object.

notEqual

A logical matrix indicating that certain pairs should not be mergedeven if they appear identical.

attribute

Which attribute(s) should be considered in comparing vertices? A vector chosen fromc("vertices", "colors", "normals", "texcoords"))

tolerance

When comparing vertices usingall.equal, this tolerancewill be used to ignore rounding error.

Value

A new mesh object.

Author(s)

Duncan Murdoch

See Also

as.mesh3d.rglId, which often constructs meshobjects containing a lot of duplication.

Examples

open3d()(mesh1 <- cuboctahedron3d(col = rainbow(14), meshColor = "face"))id <- shade3d(mesh1)(mesh2 <- as.mesh3d(id))shade3d(translate3d(mesh2, 3, 0, 0))(mesh3 <- mergeVertices(mesh2))shade3d(translate3d(mesh3, 6, 0, 0))

Construct 3D mesh objects

Description

Creates meshes containing points, segments, triangles and quads.

Usage

  mesh3d( x, y = NULL, z = NULL, vertices,                    material = NULL,                    normals = NULL, texcoords = NULL,                    points = NULL, segments = NULL,                    triangles = NULL, quads = NULL,                    meshColor = c("vertices", "edges", "faces", "legacy"))  qmesh3d(vertices, indices, homogeneous = TRUE, material = NULL,          normals = NULL, texcoords = NULL,         meshColor = c("vertices", "edges", "faces", "legacy"))  tmesh3d(vertices, indices, homogeneous = TRUE, material = NULL,          normals = NULL, texcoords = NULL,         meshColor = c("vertices", "edges", "faces", "legacy"))

Arguments

x,y,z

coordinates. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

vertices

A 4 row matrix of homogeneous coordinates; takesprecedence overx, y, z.

material

material properties for later rendering

normals

normals at each vertex

texcoords

texture coordinates at each vertex

points

vector of indices of vertices to draw as points

segments

2 x n matrix of indices of vertices to draw assegments

triangles

3 x n matrix of indices of vertices to drawas triangles

quads

4 x n matrix of indices of vertices to draw as quads

indices

(obsolete) 3 or 4 x n matrix of vertex indices

homogeneous

(obsolete) shouldtmesh3d andqmesh3d vertices be assumed to be homogeneous?

meshColor

how should colours be interpreted? See details inshade3d.

Details

These functions createmesh3d objects, which consist of a matrixof vertex coordinates together with a matrices of indices indicating how the vertices should be displayed, and material properties.

The"shape3d" class is a general class for shapes that can be plottedbydot3d,wire3d orshade3d.

The"mesh3d" class is a class of objects that form meshes: the verticesare in membervb, as a 4 byn matrix usinghomogeneous coordinates. Indices of these vertices arecontained in optional componentsip for points,is for line segments,it for triangles, andib for quads.Individual meshes may have any combination of these.

The functionstmesh3d andqmesh3d are includedfor back-compatibility; they produce meshes of triangles andquads respectively.

Value

Objects of classc("mesh3d", "shape3d").

Seepoints3d for a discussion of texture coordinates.

See Also

shade3d,shapelist3d for multiple shapes

Examples

  # generate a quad mesh object  vertices <- c(      -1.0, -1.0, 0,      1.0, -1.0, 0,      1.0,  1.0, 0,     -1.0,  1.0, 0  )  indices <- c( 1, 2, 3, 4 )    open3d()    wire3d( mesh3d(vertices = vertices, quads = indices) )

Set up multiple figure layouts

Description

Themfrow3d andlayout3d functions provide functionality in RGLsimilar topar("mfrow") andlayout in classic R graphics.

Usage

subsceneList(value, window = cur3d())mfrow3d(nr, nc, byrow = TRUE, parent = NA, sharedMouse = FALSE, ...)layout3d(mat, widths = rep.int(1, ncol(mat)),               heights = rep.int(1, nrow(mat)),              parent = NA, sharedMouse = FALSE,              ...)next3d(current = NA, clear = TRUE, reuse = TRUE)clearSubsceneList(delete = currentSubscene3d() %in% subsceneList(),                   window = cur3d())

Arguments

value

A new subscene list to set. If missing, return the current one (orNULL).

window

Which window to operate on.

nr,nc

Number of rows and columns of figures.

byrow

Whether figures progress by row (as withpar("mfrow")) or by column (as withpar("mfcol")).

mat,widths,heights

Layout parameters; seelayout for their interpretation.

parent

The parent subscene.NA indicates the current subscene. See Details below.

sharedMouse

Whether to make all subscenespar3d("listeners") to each other.

...

Additional parameters to pass tonewSubscene3d as eachsubscene is created.

current

The subscene to move away from.NA indicates the current subscene.

clear

Whether the newly entered subscene should be cleared upon entry.

reuse

Whether to skip advancing if the current subscene has no objects in it.

delete

IfTRUE, delete the subscenes in the current window.

Details

rgl can maintain a list of subscenes; themfrow3d andlayout3d functions create that list.When the list is in place,next3d causes RGL to move to the next scene in the list, or cycleback to the first one.

Unlike the classic R graphics versions of these functions, these functions are completely compatible witheach other. You can mix them within a single RGL window.

In the default case whereparent is missing,mfrow3d andlayout3d willcallclearSubsceneList() at the start.

By defaultclearSubsceneList() checkswhether the current subscene is in the current subscene list; if so, it will deleteall subscenes in the list, and callgc3d to delete any objects that are nolonger shown. The subscene list will be set to a previous value if one was recorded,orNULL if not.

Ifparent is specified inmfrow3d orlayout3d (even asNA), the new subscenes will be created within the parent.

Thenext3d() function first finds out if the currentsubscene is in the current list. If not, it moves to theprevious list, and looks there. Once it finds a list containing the current subscene, it moves to the next entryin that list. If it can't find one, it creates a lengthone list containing just the current subscene.

Value

mfrow3d andlayout3d return a vector of subscene id values that have just beencreated. If a previous subscene list was in effect and was not automatically cleared,it is attached as an attribute"prev".

Author(s)

Duncan Murdoch

See Also

newSubscene3d,par,layout.

Examples

shapes <- list(Tetrahedron = tetrahedron3d(), Cube = cube3d(), Octahedron = octahedron3d(),               Icosahedron = icosahedron3d(), Dodecahedron = dodecahedron3d(),               Cuboctahedron = cuboctahedron3d())col <- rainbow(6)open3d()mfrow3d(3, 2)for (i in 1:6) {  next3d()   # won't advance the first time, since it is empty  shade3d(shapes[[i]], col = col[i])}highlevel(integer()) # To trigger display as rglwidgetopen3d()mat <- matrix(1:4, 2, 2)mat <- rbind(mat, mat + 4, mat + 8)layout3d(mat, height = rep(c(3, 1), 3), sharedMouse = TRUE)for (i in 1:6) {  next3d()  shade3d(shapes[[i]], col = col[i])  next3d()  text3d(0, 0, 0, names(shapes)[i])}highlevel(integer())

Set the observer location

Description

This function sets the location of the viewer.

Usage

observer3d(x, y = NULL, z = NULL, auto = FALSE)

Arguments

x,y,z

The location as a 3 vector, using the usualxyz.coordsconventions for specification. Ifx is missingor any coordinate isNA, no change will be made to thelocation.

auto

IfTRUE, the location will be set automatically by RGL to make the whole bounding box visible.

Details

This functionsets the location of the viewer relative to the scene, after the model transformations(scaling, rotation) have been done, but before lighting or projection have been applied. (Seepar3d for details on the rendering pipeline.)

The coordinate system is a slightly strange one: the X coordinatemoves the observer location from left to right, and the Y coordinate moves upand down. The Z coordinate changes the depth from the viewer. All are measuredrelative to the center of the bounding box (par("bbox")) of the subscene.The observer always looks in the positive Z directionafter the model rotation have been done. The coordinates are in post-scalingunits.

Value

Invisibly returns the previous value.

Note

This function is likely to change in future versions of RGL, to allow more flexibility in the specification of the observer's location and orientation.

Author(s)

Duncan Murdoch

Examples

example(surface3d)  # The volcano dataobserver3d(0, 0, 440) # Viewed from very close up

Work with RGL windows

Description

open3d opens a new RGL window;cur3d returns the device number of the currentwindow;close3d closes one or more windows.

Usage

open3d(..., params = getr3dDefaults(),     useNULL = rgl.useNULL(), silent = FALSE)    close3d(dev = cur3d(), silent = TRUE)    cur3d()rgl.dev.list()set3d(dev, silent = FALSE)getr3dDefaults(class = NULL, value = NULL)r3dDefaultsrgl.quit()

Arguments

...

arguments inname = value form, or a list of namedvalues. The names must come from the graphicalparameters described inpar3d.

params

a list of graphical parameters

useNULL

whether to use the null graphics device

dev

which device to close or use

silent

whether report on what was done

class,value

names of components to retrieve

Details

open3d opens a new RGL device, and sets the parameters asrequested. Ther3dDefaults list returned by thegetr3dDefaults function will be used as defaultvalues for parameters. As installed this sets the point of view to'world coordinates' (i.e. x running from left to right, y from frontto back, z from bottom to top), themouseMode to(zAxis, zoom, fov), and the field of view to 30 degrees.useFreeType defaults toFALSE on Windows; on other systems it indicates the availabilityof FreeType.Users may create their own variable namedr3dDefaults in the globalenvironment and it will override the installed one. If thereis abg element in the list or the arguments, it should bea list of arguments to pass to thebg3d function to set the background.

The arguments toopen3d may includematerial, a listof material properties as inr3dDefaults, but notethat high level functions such asplot3d normally usether3dDefaults values in preference to this setting.

IfuseNULL isTRUE, RGL will use a “null”device. This device records objects as they are plotted, but displays nothing. It is intended for use withrglwidget.

Value

Theopen3d function returns the device that was opened. Ifsilent = TRUE, it is returned invisibly.

Thecur3d function returns the current device,or the value 0 if there isn't one.rgl.dev.listreturns a vector of all open devices. Items are namedaccording to the type of device:null for a hiddennull device,wgl for a Windows device, andglX for an X windows device.

set3d returns the device number of thepreviously active device.

Theclose3d function returns the new currentdevice, invisibly.

Ther3dDefaults variable is a list containing defaultsettings. Thegetr3dDefaults function searches the user'sglobal environment forr3dDefaults and returns the one in the RGL namespace if it was not found there.The components of the list may include any settablepar3dparameter, or"material", which should include a listof defaultmaterial3d properties, or"bg", which is alist of defaults to pass to thebg3d function.

rgl.quit attempts to unloadrgl and then returnsNULL invisibly.

See Also

rgl.useNULL for default usage of null device.

Examples

    r3dDefaults    open3d()    shade3d(cube3d(color = rainbow(6), meshColor = "faces"))    cur3d()

Set or query RGL parameters

Description

par3d can be used to set or query graphical parameters in RGL.Parameters can be set by specifying them as arguments topar3d inname = value form, or by passing them as a list of namedvalues.

Usage

par3d(..., no.readonly = FALSE, dev = cur3d(),       subscene = currentSubscene3d(dev))rgl.par3d.namesrgl.par3d.readonly

Arguments

...

arguments inname = value form, or a list of taggedvalues. The names must come from the graphical parameters describedbelow.

no.readonly

logical; ifTRUE and there are no otherarguments, only those parameters which can be set by asubsequentpar3d() call are returned.

dev

integer; the RGL device.

subscene

integer; the subscene.

Details

Parameters are queried by giving one or more character vectors topar3d.

par3d() (no arguments) orpar3d(no.readonly = TRUE) is used togetall the graphical parameters (as a named list).

By default, queries and modifications apply to the current subsceneon the current device; specifydev and/orsubscene to change this. Some parameters apply to the device as a whole;these are marked in the list below.

Value

When parameters are set, their former values are returned in aninvisible named list. Such a list can be passed as an argument topar3d to restore the parameter values.Usepar3d(no.readonly = TRUE) for the full list of parametersthat can be restored.

When just one parameter is queried, its value is returned directly.When two or more parameters are queried, the result is a list ofvalues, with the list names giving the parameters.

Note the inconsistency: setting one parameter returns a list, butquerying one parameter returns an object.

Parameters

Thergl.par3d.names variable contains thefull list of names ofpar3d properties.rgl.par3d.readonly contains the list ofread-only properties.

In the list below,R.O. indicates theread-only arguments: These may only be used inqueries, they do not set anything.

activeSubscene

R.O. integer. Usedwithrgl.setMouseCallbacks: during a callback, indicates the id of the subscene that was clicked.

antialias

R.O. inpar3d, may beset inopen3d. The (requested) number of hardwareantialiasing planes to use (with multisample antialiasing). TheOpenGL driver may not support the requested number, in which casepar3d("antialias") will report what was actually set. Applies to the whole device.

cex

real. The default size for text.

family

character. The default device independent family name; seetext3d.Applies to the whole device.

font

integer. The default font number (from 1 to 4; seetext3d).Applies to the whole device.

useFreeType

logical. Should FreeType fonts be used?Applies to the whole device.

fontname

R.O.; the system-dependent name of the current font.Applies to the whole device.

FOV

real. The field of view, from 0 to 179 degrees. This controlsthe degree of parallax in the perspective view.Isometric perspective corresponds toFOV = 0.

ignoreExtent

logical. Set toTRUE so that subsequently plotted objectswill be ignored in calculating the bounding box of the scene. Applies to thewhole device.

maxClipPlanes

R.O.; an integer giving the maximumnumber of clip planes that can be defined in the current system. Applies to the whole device.

modelMatrix

R.O.; a 4 by 4 matrix describing the positionof the user data. See the Note below.

listeners

integer. A vector of subscene id values. If a subscene receivesa mouse event (seemouseMode just below), the same action will be carried outon all subscenes in this list. (The subscene itself is normally listed as a listener.If it is not listed, it will not respond to its own mouse events.)

mouseMode

character. A vector of 5 strings describingmouse actions. The 5 entries are namedc("none", "left", "right", "middle", "wheel"), corresponding to actions for no button, the left, right or middle button, and the mouse wheel.Partial matching to action names is used. Possible values for the actions are:

"none"

No action for this button.

"trackball"

Mouse acts as a virtual trackball, rotating the scene.

"xAxis"

Similar to"trackball", but restricted to X axis rotation.

"yAxis"

Y axis rotation.

"zAxis"

Z axis rotation.

"polar"

Mouse rotates the scene by moving in polar coordinates.

"selecting"

Mouse is used for selection. This is not normally set by theuser, but is used internally by theselect3d function.

"zoom"

Mouse is used to zoom the display.

"fov"

Mouse changes the field of view of the display.

"user"

Used when a user handler is set byrgl.setMouseCallbacks.

Possible values for the last entry corresponding to the mouse wheel also include

"pull"

Pulling on the mouse wheel increases magnification, i.e. “pulls the scene closer”.

"push"

Pulling on the mouse wheel decreases magnification, i.e. “pushes the scene away”.

"user2"

Used when a user handler is set byrgl.setWheelCallback.

A common default on Mac OSX is to convert a two finger drag on a trackpad to a mouse wheel rotation.

The first entry is for actions to take whenno mouse button is pressed. Legal values are the sameas for the mouse buttons.

The first entry was added afterrgl version 0.106.8. For back compatibility, if the vectorof actions is less than 5 entries,"none"will be added at the start of it.

observer

R.O.; the position of the observer relative tothe model. Set byobserver3d. See the Note below.

projMatrix

R.O.; a 4 by 4 matrix describing the currentprojection of the scene.

scale

real. A vector of 3 values indicating the amount by which torescale each axis before display. Set byaspect3d.

skipRedraw

whether to update the display. Set toTRUE to suspendupdating while making multiple changes to the scene. Seedemo(hist3d) for an example.Applies to the whole device.

userMatrix

a 4 by 4 matrix describing user actions todisplay the scene.

userProjection

a 4 by 4 matrix describingchanges to the projection.

viewport

real. A vector giving the dimensions of thewindow in pixels. The entries are taken to bec(x, y, width, height) wherec(x, y) are the coordinates in pixels of the lower left corner within the window.

zoom

real. A positive value indicating the currentmagnification of the scene.

bbox

R.O.; real. A vector of six values indicating the current values of thebounding box of the scene (xmin, xmax, ymin, ymax, zmin, zmax)

windowRect

integer. A vector of four values indicating the left, top, right and bottom of the displayed window (in pixels). Applies to the whole device.

Rendering

The parameters returned bypar3d are sufficient to determine where RGL would rendera point on the screen. Given a column vector(x, y, z) in a subscenes, it performs the equivalent of the following operations:

  1. It converts the point to homogeneous coordinates by appendingw = 1, givingthe vectorv = (x, y, z, 1).

  2. It calculates theM = par3d("modelMatrix") as a product from right to leftof several matrices:

    • A matrix to translate the centre of the bounding box to the origin.

    • A matrix to rescale according topar3d("scale").

    • Thepar3d("userMatrix") as set by the user.

    • A matrix which may be set by mouse movements.

    • The description above applies to the usual case where there is just one subscene, or where the subscene's"model" is set to"replace". If it is set to"modify", the first step isskipped, and at the end the procedure is followed for the parent subscene. If it is set to"inherit" only the parent settingsare used.

  3. It multiplies the point byM givingu = M %*% v.

  4. It multiplies that point by a matrix based on the observer positionto translate the origin to the centre of the viewing region.

  5. Using this location and information on thenormals (which have been similarly transformed), it performs lighting calculations.

  6. It obtains the projection matrixP = par3d("projMatrix") based on the bounding box and field of viewor observer location, multiplies that by theuserProjection matrix to giveP. It multiplies the pointby it givingP %*% u = (x2, y2, z2, w2).

  7. It converts back to Euclidean coordinates by dividing the first 3 coordinates byw2.

  8. The new valuez2/w2 represents the depth into the scene of the point. Dependingon what has already been plotted, this depth might be obscured, in which case nothing more is plotted.

  9. If the point is not culled due to depth, thex2 andy2 values are usedto determine the point in the image. Thepar3d("viewport") values are used to translatefrom the range(-1, 1) to pixel locations, and the point is plotted.

  10. If hardware antialiasing is enabled, then the whole process isrepeated multiple times (at least conceptually) with differentlocations in each pixel sampled to determine what is plotted there,and then the images are combined into what is displayed.

See ?matrices for more information on homogeneous and Euclidean coordinates.

Note that many of these calculations are done on the graphics card using single precision;you will likely see signs of rounding error if your scene requires more than 4 or 5 digit precision to distinguish values in any coordinate.

Note

The"xAxis","yAxis" and"zAxis" mouse modes rotate relative to the coordinate system of the data, regardless of the current orientation of the scene.

When multiple parameters are set, they are set in the order given. In some cases this may lead to warnings and ignored values; for example, some font families only supportcex = 1, so changing bothcex andfamily needs to be done in the right order. For example, when using the"bitmap" family on Windows,par3d(family = "sans", cex = 2)will work, butpar3d(cex = 2, family = "sans") will leavecexat 1 (with a warning that the"bitmap" family only supports that size).

Althoughpar3d("viewport") names the entries of the reported vector,names are ignored when setting the viewport and entries must be specifiedin the standard order.

Inrgl versions 0.94.x themodelMatrix entry had a changed meaning; before and after that it contains a copy of the OpenGL MODELVIEW matrix.

As of version 0.100.32, when changing the"windowRect" parameter, the"viewport" for the root (or specified) subsceneis changed immediately. This fixes a bug where in earlierversions it would only be changed when the window was redrawn, potentially after another command making use of the value.

Default values are not described here, as several of themare changed by ther3dDefaults variable whenthe window is opened byopen3d.

References

OpenGL Architecture Review Board (1997). OpenGL Programming Guide. Addison-Wesley.

See Also

view3d to setFOV andzoom.

open3d for how to open a new windowwith default settings for these parameters.

Examples

    open3d()    shade3d(cube3d(color = rainbow(6), meshColor = "faces"))    save <- par3d(userMatrix = rotationMatrix(90*pi/180, 1, 0, 0))    highlevel()  # To trigger display    save    par3d("userMatrix")        par3d(save)    highlevel()    par3d("userMatrix")

Interpolator for par3d parameters

Description

Returns a function which interpolatespar3d parameter values,suitable for use in animations.

Usage

par3dinterp(times = NULL, userMatrix, scale, zoom, FOV,             method = c("spline", "linear"),             extrapolate = c("oscillate", "cycle", "constant", "natural"),            dev = cur3d(), subscene = par3d("listeners", dev = dev))

Arguments

times

Times at which values are recorded or a list; see below

userMatrix

Values ofpar3d("userMatrix")

scale

Values ofpar3d("scale")

zoom

Values ofpar3d("zoom")

FOV

Values ofpar3d("FOV")

method

Method of interpolation

extrapolate

How to extrapolate outside the time range

dev

Which RGL device to use

subscene

Which subscene to use

Details

This function is intended to be used in constructing animations. It producesa function that returns a list suitable to pass topar3d, to set the viewpoint at a given point in time.

All of the parameters are optional. Only thosepar3d parameters that are specified will be returned.

The input values other thantimes may each be specified aslists, giving the parameter value settings at a fixed time, or asmatrices or arrays. If not lists, the following formats should beused:userMatrix can be a4 x 4 x n array, or a4x 4n matrix;scale should be ann x 3 matrix;zoom andFOV should be lengthn vectors.

An alternative form of input is to put all of the above arguments intoa list (i.e. a list of lists, or a list of arrays/matrices/vectors),and pass it as the first argument. This is the most convenient way touse this function with the functiontkpar3dsave.

Interpolation is by cubic spline or linear interpolation in an appropriatecoordinate-wise fashion. Extrapolation may oscillate(repeat the sequence forward, backward, forward, etc.), cycle (repeatit forward), be constant (no repetition outside the specified timerange), or be natural (linear on an appropriate scale). In the case of cycling, the first and last specified valuesshould be equal, or the last one will be dropped. Natural extrapolationis only supported with spline interpolation.

Value

A function is returned. The function takes one argument, and returns a list ofpar3d settings interpolated to that time.

Note

Prior torgl version 0.95.1476, thesubscene argument defaulted to thecurrent subscene, and any additional entries wouldbe ignored byplay3d. The currentdefault value ofpar3d("listeners", dev = dev) means that all subscenes that share mouse responses will also share modificationsby this function.

Author(s)

Duncan Murdoch

See Also

play3d to play the animation.

Examples

f <- par3dinterp( zoom = c(1, 2, 3, 1) )f(0)f(1)f(0.5)## Not run: play3d(f)## End(Not run)

Control RGL widget like par3dinterp()

Description

This control works withplaywidget to change settings in a WebGL display in the same wayaspar3dinterp does within R.

Usage

par3dinterpControl(fn, from, to, steps, subscene = NULL, omitConstant = TRUE, ...)

Arguments

fn

A function returned frompar3dinterp.

from,to,steps

Values wherefn should be evaluated.

subscene

Which subscene's properties should be modified?

omitConstant

IfTRUE, do not set values that areconstant across the range.

...

Additional parameters which will be passedtopropertyControl.

Details

par3dinterpSetter sets parameters corresponding to values produced by the result ofpar3dinterp.

Value

Returns controller data in a list of class "rglControl".

Author(s)

Duncan Murdoch

See Also

TheUser Interaction in WebGL vignettegives more details.

Examples

example(plot3d)M <- r3dDefaults$userMatrixfn <- par3dinterp(times = (0:2)*0.75, userMatrix = list(M,                                      rotate3d(M, pi/2, 1, 0, 0),                                      rotate3d(M, pi/2, 0, 1, 0)),                                      scale = c(0.5, 1, 2))control <- par3dinterpControl(fn, 0, 3, steps = 15)control      if (interactive() || in_pkgdown_example())   rglwidget(width = 500, height = 250) %>%  playwidget(control,       step = 0.01, loop = TRUE, rate = 0.5)

Plot symbols similar to base graphics

Description

This function plots symbols similarly to what the base graphics functionpoints does whenpch is specified.

Usage

pch3d(x, y = NULL, z = NULL, pch = 1,       bg = material3d("color")[1], cex = 1, radius,       color = "black", lit = FALSE, ...)

Arguments

x,y,z

The locations at which to plot in a formsuitable for use inxyz.coords.

pch

A vector of integers or single charactersdescribing the symbols to plot.

bg

The fill color(s) to use forpch from 21 to 25.

cex

A relative size of the symbol to plot.

radius

An absolute size of the symbol to plot in user coordinates.

color

The color(s) to use for symbols.

lit

Whether the object responds to lighting or just shows thedisplayed color directly.

...

Other material properties.

Details

The list of symbols encoded by numericalpch values is given in thepoints help page.

Value

A vector of object id values is returned invisibly. Separate objects will be drawnfor each different combination ofpch value from 0 to 25,color andbg, and another holding all the charactersymbols.

Note

This function is not a perfect match to how thepoints function works dueto limitations in RGL and OpenGL. Inparticular:

Symbols with numbers from 1 to 25 are drawnas 3D sprites (seesprites3d),so they will resize as the window is zoomed.Letters and numbers from 32 to 255 (which aremapped to letters) are drawn usingtext3d, so they maintain a fixed size.

A calculation somewhat like the one inplot3d that sets the sizeof spheres is used to choose the size ofsprites based oncex and the current scaling. This will likely need manualtweaking. Use theradius argumentfor a fixed size.

No special handling is done for the case ofpch = ".". Usepoints3d for small dots.

As ofrgl version 0.100.10, background and foreground colors can vary from symbol to symbol.

Author(s)

Duncan Murdoch

See Also

points3d,text3d andsprites3d for other ways to label points,points for the base graphics symboldefinitions.

Examples

open3d()i <- 0:25; x <- i %% 5; y <- rep(0, 26); z <- i %/% 5pch3d(x, y, z, pch = i, bg = "gray", color = rainbow(26))text3d(x, y, z + 0.3, i)pch3d(x + 5, y, z, pch = i+65)text3d(x + 5, y, z + 0.3, i+65)

Surface plots

Description

This function draws plots of surfaces in 3-space.persp3d is a generic function.

Usage

persp3d(x, ...)## Default S3 method:persp3d(x = seq(0, 1, length.out = nrow(z)),    y = seq(0, 1, length.out = ncol(z)), z,    xlim = NULL, ylim = NULL, zlim = NULL,    xlab = NULL, ylab = NULL, zlab = NULL, add = FALSE, aspect = !add,     forceClipregion = FALSE, ...)

Arguments

x,y,z

points to plot on surface. See Details below.

xlim,ylim,zlim

x-, y- and z-limits. If present,the plot is clipped to this region.

xlab,ylab,zlab

titles for the axes. N.B. These must becharacter strings; expressions are not accepted. Numbers will becoerced to character strings.

add

whether to add the points to an existing plot.

aspect

either a logical indicating whether to adjust the aspect ratio, or a new ratio.

forceClipregion

force a clipping region to be used,whether or not limits are given.

...

additional material parameters to be passed tosurface3danddecorate3d.

Details

The default method plots a surface defined as a grid of(x,y,z) locations in space. The grid may be specified in several ways:

One difference frompersp is that colors are specified on eachvertex, rather than on each facet of the surface. To emulate theperspcolor handling, you need to do the following. First, convert the color vector to an(nx - 1) by(ny - 1) matrix; then add an extra row before row 1, and an extra column after the last column, to convert it tonx byny.(These extra colors will not be used). For example,col <- rbind(1, cbind(matrix(col, nx - 1, ny - 1), 1)).Finally, callpersp3d with material propertysmooth = FALSE.

See the “Clipping” section inplot3dfor more details onxlim, ylim, zlim andforceClipregion.

Value

This function is called for the side effect of drawing the plot. A vector of shape IDs is returned invisibly.

Author(s)

Duncan Murdoch

See Also

plot3d,persp. There isapersp3d.function method for drawing functions, andpersp3d.deldir can be usedto draw surfaces defined by an irregular collection of points. A formula methodpersp3d.formula draws surfaces using this method.

Thesurface3d function is used to draw the surface without the axes etc.

Examples

# (1) The Obligatory Mathematical surface.#     Rotated sinc function.x <- seq(-10, 10, length.out = 20)y <- xf <- function(x, y) { r <- sqrt(x^2 + y^2); 10 * sin(r)/r }z <- outer(x, y, f)z[is.na(z)] <- 1open3d()# Draw the surface twice:  the first draws the solid part, # the second draws the grid.  Offset the first so it doesn't# obscure the lines.persp3d(x, y, z, aspect = c(1, 1, 0.5), col = "lightblue",        xlab = "X", ylab = "Y", zlab = "Sinc( r )",         polygon_offset = 1)persp3d(x, y, z, front = "lines", back = "lines",         lit = FALSE, add = TRUE)highlevel()   # trigger the plot# (2) Add to existing persp plot:xE <- c(-10, 10); xy <- expand.grid(xE, xE)points3d(xy[, 1], xy[, 2], 6, col = "red")lines3d(x, y = 10, z = 6 + sin(x), col = "green")phi <- seq(0, 2*pi, length.out = 201)r1 <- 7.725 # radius of 2nd maximumxr <- r1 * cos(phi)yr <- r1 * sin(phi)lines3d(xr, yr, f(xr, yr), col = "pink", lwd = 2)# (3) Visualizing a simple DEM modelz <- 2 * volcano        # Exaggerate the reliefx <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)open3d()invisible(bg3d("slategray")) # suppress displaymaterial3d(col = "black")persp3d(x, y, z, col = "green3", aspect = "iso",      axes = FALSE, box = FALSE)# (4) A globelat <- matrix(seq(90, -90, length.out = 50)*pi/180, 50, 50, byrow = TRUE)long <- matrix(seq(-180, 180, length.out = 50)*pi/180, 50, 50)r <- 6378.1 # radius of Earth in kmx <- r*cos(lat)*cos(long)y <- r*cos(lat)*sin(long)z <- r*sin(lat)open3d()persp3d(x, y, z, col = "white",        texture = system.file("textures/worldsmall.png", package = "rgl"),        specular = "black", axes = FALSE, box = FALSE, xlab = "", ylab = "", zlab = "",       normal_x = x, normal_y = y, normal_z = z)## Not run: # This looks much better, but is slow because the texture is very bigpersp3d(x, y, z, col = "white",        texture = system.file("textures/world.png", package = "rgl"),        specular = "black", axes = FALSE, box = FALSE, xlab = "", ylab = "", zlab = "",       normal_x = x, normal_y = y, normal_z = z)## End(Not run)

Plot a Delaunay triangulation

Description

Thedeldir() function in thedeldir package computes a Delaunay triangulation of a setof points. These functions display it as a surface.

Usage

## S3 method for class 'deldir'plot3d(x, ...)## S3 method for class 'deldir'persp3d(x, ..., add = FALSE)## S3 method for class 'deldir'as.mesh3d(x, col = "gray", coords = c("x", "y", "z"),     smooth = TRUE, normals = NULL, texcoords = NULL, ...)

Arguments

x

A"deldir" object, produced by thedeldir() function. It must containz values.

add

Whether to add surface to existing plot (add = TRUE)or create a new plot (add = FALSE, the default).

col

Colors to apply to each vertex in the triangulation.Will be recycled as needed.

coords

See Details below.

smooth

Whether to average normals at vertices fora smooth appearance.

normals

User-specified normals at each vertex. Requiressmooth = FALSE.

texcoords

Texture coordinates at each vertex.

...

See Details below.

Details

These functions construct amesh3d objectcorresponding to the triangulation inx. Theplot3d andpersp3d methods plot it.

Thecoords parameter allows surfaces to be plotted over any coordinate plane. It should bea permutation of the column namesc("x", "y", "z")from the"deldir" object. The first will be usedas the x coordinate, the second as the y coordinate, and the third as the z coordinate.

The... parameters inplot3d.deldir are passed topersp3d.deldir; inpersp3d.deldir they arepassed to bothas.mesh3d.deldir andpersp3d.mesh3d; inas.mesh3d.deldir they are used as material parametersin atmesh3d call.

Examples

x <- rnorm(200, sd = 5)y <- rnorm(200, sd = 5)r <- sqrt(x^2 + y^2)z <- 10 * sin(r)/rcol <- cm.colors(20)[1 + round(19*(z - min(z))/diff(range(z)))]save <- options(rgl.meshColorWarning = FALSE)# This code is awkward:  to work with demo(rglExamples),# we need auto-printing of the plots.  This means we# have to repeat the test for deldir.haveDeldir <- checkDeldir()              if (haveDeldir) {  dxyz <- deldir::deldir(x, y, z = z, suppressMsge = TRUE)  persp3d(dxyz, col = col)}if (haveDeldir) {  open3d()  # Do it without smoothing and with a different orientation.  persp3d(dxyz, col = col, coords = c("z", "x", "y"), smooth = FALSE)}options(save)

Plot a function of two variables

Description

Plot a functionz(x, y) or a parametric function(x(s, t), y(s, t), z(s, t)).

Usage

## S3 method for class ''function''persp3d(x,   xlim = c(0, 1), ylim = c(0, 1),   slim = NULL, tlim = NULL,   n = 101,   xvals = seq.int(min(xlim), max(xlim), length.out = n[1]),   yvals = seq.int(min(ylim), max(ylim), length.out = n[2]),   svals = seq.int(min(slim), max(slim), length.out = n[1]),   tvals = seq.int(min(tlim), max(tlim), length.out = n[2]),   xlab, ylab, zlab,   col = "gray", otherargs = list(),   normal = NULL, texcoords = NULL, ...)## S3 method for class ''function''plot3d(x, ...)

Arguments

x

A function of two arguments. See the details below.

xlim,ylim

By default, the range of x and y values. For a parametricsurface, if these are not missing, they are used as limitson the displayed x and y values.

slim,tlim

If notNULL, these give the range of s and t in theparametric specification of the surface. Ifonly one is given, the other defaults toc(0, 1).

n

A one or two element vector giving the number of steps in the x and y (or s and t) grid.

xvals,yvals

The values at which to evaluate x and y. Ignored fora parametric surface. If used,xlim and/orylimare ignored.

svals,tvals

The values at which to evaluate s and t for a parametricsurface. Only used ifslim ortlim is notNULL. As withxvals andyvals, these override the correspondingslim ortlim specification.

xlab,ylab,zlab

The axis labels. See the details below for the defaults.

col

The color to use for the plot. See the details below.

otherargs

Additional arguments to pass to the function.

normal,texcoords

Functions to set surface normals or texture coordinates. Seethe details below.

...

Additional arguments to pass topersp3d.

Details

The"function" method forplot3d simply passesall arguments topersp3d. Thus this description appliesto both.

The first argumentx is required to be a function. Itis namedx only because of the requirements of the S3system; in the remainder of this help page, we will assumethat the assignmentf <- x has been made, and will refer to the functionf().

persp3d.function evaluatesf() on a two-dimensionalgrid of values, and displays the resulting surface. The valueson the grid will be passed in as vectors in the first two arguments to the function, sof() needsto be vectorized. Other optional arguments tof()can be specified in theotherargs list.

In the default form whereslim andtlim are bothNULL, it is assumed thatf(x, y) returns heights,which will be plotted in the z coordinate. The default axis labelswill be taken from the argument names tof() and theexpression passed as argumentx to this function.

Ifslim ortlim is specified, a parametricsurface is plotted. The functionf(s, t) must return a 3-column matrix, giving x, y and z coordinates of points on the surface. The default axislabels will be the column names if those are present.In this casexlim,ylim andzlimare used to define a clipping region only if specified;the defaults are ignored.

The color of the surface may be specified as the name of acolor, or a vector or matrix of color names. In this casethe colors will be recycled across the points on the gridof values.

Alternatively, a function may be given: it should be a functionlikerainbow that takes an integer argument andreturns a vector of colors. In this case the colors are mappedto z values.

Thenormal argument allows specification of a functionto compute normal vectors to the surface. This function ispassed the same arguments asf() (includingotherargsif present), and should produce a 3-column matrix containing thex, y and z coordinates of the normals.

Thetexcoords argument is a function similar tonormal, butit produces a 2-column matrix containing texture coordinates.

Bothnormal andtexcoords may also contain matrices,with 3 and 2 columns respectively, and rows corresponding to thepoints that were passed tof().

Value

This function constructs a call topersp3dand returns the value from that function.

Author(s)

Duncan Murdoch

See Also

Thecurve function in base graphics doessomething similar for functions of one variable. See theexample below for space curves.

Examples

# (1) The Obligatory Mathematical surface.#     Rotated sinc function, with colorsf <- function(x, y) {   r <- sqrt(x^2 + y^2)  ifelse(r == 0, 10, 10 * sin(r)/r)}open3d()plot3d(f, col = colorRampPalette(c("blue", "white", "red")),        xlab = "X", ylab = "Y", zlab = "Sinc( r )",        xlim = c(-10, 10), ylim = c(-10, 10),       aspect = c(1, 1, 0.5))       # (2) A cylindrical plotf <- function(s, t) {  r <- 1 + exp( -pmin( (s - t)^2,                        (s - t - 1)^2,                        (s - t + 1)^2 )/0.01 )  cbind(r*cos(t*2*pi), r*sin(t*2*pi), s)}open3d()plot3d(f, slim = c(0, 1), tlim = c(0, 1), col = "red", alpha = 0.8)# Add a curve to the plot, fixing s at 0.5.plot3d(f(0.5, seq.int(0, 1, length.out = 100)), type = "l", add = TRUE,        lwd = 3, depth_test = "lequal")

Plot an interp Delaunay triangulation

Description

Thetri.mesh() function in theinterp package computes a Delaunay triangulation of a setof points. These functions display it as a surface.

Usage

## S3 method for class 'triSht'plot3d(x, z, ...)## S3 method for class 'triSht'persp3d(x, z, ..., add = FALSE)## S3 method for class 'triSht'as.mesh3d(x, z, col = "gray", coords = c("x", "y", "z"),     smooth = TRUE, normals = NULL, texcoords = NULL, ...)

Arguments

x

A"triSht" object, produced by thetri.mesh() function in theinterp package.

z

z coordinate values corresponding to each of the nodes inx.

add

Whether to add surface to existing plot (add = TRUE)or create a new plot (add = FALSE, the default).

col

Colors to apply to each vertex in the triangulation.Will be recycled as needed.

coords

See Details below.

smooth

Whether to average normals at vertices fora smooth appearance.

normals

User-specified normals at each vertex. Requiressmooth = FALSE.

texcoords

Texture coordinates at each vertex.

...

See Details below.

Details

These functions construct amesh3d objectcorresponding to the triangulation inx. Theplot3d andpersp3d methods plot it.

Thecoords parameter allows surfaces to be plotted over any coordinate plane. It should bea permutation of the column namesc("x", "y", "z").The first will be usedas the x coordinate, the second as the y coordinate, and the third as the z coordinate.

The... parameters inplot3d.triSht andplot3d.tri are passed topersp3d; inpersp3d.triShtandpersp3d.tri they arepassed to bothas.mesh3d andpersp3d.mesh3d; inas.mesh3d.triSht andas.mesh3d.tri they are used as material parametersin atmesh3d call.

"tri" objects may contain constraints. These appearinternally as extra nodes, representing either the insideor outside of boundaries on the region being triangulated.Each of these nodes should also have az value, but triangles corresponding entirely to constraint nodes will notbe drawn. In this way complex, non-convex regions canbe triangulated. See the second example below.

Note

If there are duplicate points, thetri.mesh() functionswill optionally delete some of them. If you choose this option,thez values must correspond to the nodesafterdeletion, not before.

Examples

x <- rnorm(200, sd = 5)y <- rnorm(200, sd = 5)r <- sqrt(x^2 + y^2)z <- 10 * sin(r)/rcol <- cm.colors(20)[1 + round(19*(z - min(z))/diff(range(z)))]save <- NULLif ((haveinterp <- requireNamespace("interp", quietly = TRUE))) {  save <- options(rgl.meshColorWarning = FALSE)  dxy <- interp::tri.mesh(x, y)  open3d()  persp3d(dxy, z, col = col, meshColor = "vertices")}if (haveinterp) {  open3d()  # Do it without smoothing and with a different orientation.  persp3d(dxy, z, col = col, coords = c("z", "x", "y"), smooth = FALSE)}options(save)

Add planes

Description

planes3d adds mathematical planes to a scene. Their intersection with the currentbounding box will be drawn.clipplanes3d adds clipping planes to a scene.

Usage

planes3d(a, b = NULL, c = NULL, d = 0, ...)clipplanes3d(a, b = NULL, c = NULL, d = 0)

Arguments

a,b,c

Coordinates of the normal to the plane. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

d

Coordinates of the "offset". See the details.

...

Material properties. Seematerial3d for details.

Details

planes3d draws planes using the parametrizationa x + b y + c z + d = 0. Multiple planes may be specifiedby giving multiple values for any ofa, b, c, d; the other values will be recycled as necessary.

clipplanes3d defines clipping planesusing the same equations. Clipping planes suppress the display ofother objects (or parts of them) in the subscene, based on their coordinates.Points (or parts of lines or surfaces) where the coordinatesx, y, zsatisfya x + b y + c z + d < 0 will be suppressed.

The number of clipping planessupported by the OpenGL driver is implementation dependent; usepar3d("maxClipPlanes") to find the limit.

Value

A shape ID of the planes or clipplanes object is returned invisibly.

See Also

abclines3d for mathematical lines.

triangles3d or the correspondingfunctions for quadrilaterals may be used to draw sections of planes thatdo not adapt to the bounding box.

The example insubscene3d shows how to combine clipping planesto suppress complex shapes.

Examples

# Show regression plane with z as dependent variableopen3d()x <- rnorm(100)y <- rnorm(100)z <- 0.2*x - 0.3*y + rnorm(100, sd = 0.3)fit <- lm(z ~ x + y)plot3d(x, y, z, type = "s", col = "red", size = 1)coefs <- coef(fit)a <- coefs["x"]b <- coefs["y"]c <- -1d <- coefs["(Intercept)"]planes3d(a, b, c, d, alpha = 0.5)open3d()ids <- plot3d(x, y, z, type = "s", col = "red", size = 1, forceClipregion = TRUE) oldid <- useSubscene3d(ids["clipregion"])clipplanes3d(a, b, c, d)useSubscene3d(oldid)

Play animation of RGL scene

Description

play3d calls a function repeatedly, passing it the elapsedtime in seconds, and using the result of the function toreset the viewpoint.movie3d does the same, butrecords each frame to a file to make a movie.

Usage

play3d(f, duration = Inf, dev = cur3d(), ..., startTime = 0)movie3d(f, duration, dev = cur3d(), ..., fps = 10,                     movie = "movie", frames = movie, dir = tempdir(),                     convert = NULL, clean = TRUE, verbose = TRUE,                    top = !rgl.useNULL(), type = "gif", startTime = 0,                    webshot = TRUE)

Arguments

f

A function returning a list that may be passed topar3d

duration

The duration of the animation

dev

Which RGL device to select

...

Additional parameters to pass tof.

startTime

Initial time at which to start the animation

fps

Number of frames per second

movie

The base of the output filename, not including .gif

frames

The base of the name for each frame

dir

A directory in which to create temporary files for each frame of the movie

convert

How to convert to a GIF movie; see Details

clean

Ifconvert isNULL orTRUE, whether to delete the individual frames

verbose

Whether to report theconvert command and the output filename

top

Whether to callrgl.bringtotop before each frame

type

What type of movie to create. See Details.

webshot

Whether to use thewebshot2 packagefor snapshots of frames. Seesnapshot3d.

Details

The functionf will be called in a loop with the first argumentbeing thestartTime plus the time in seconds since the start (where the start is measured after all arguments have been evaluated).

play3d is likely to place a high loadon the CPU; if this is a problem, calls toSys.sleepshould be made within the function to release time to other processes.

play3d will run for the specifiedduration (in seconds), butcan be interrupted by pressingESC while the RGL window has the focus.

movie3d saves each frame to disk in a filename of the form ‘framesXXX.png’, whereXXX is the frame number, starting from 0. Ifconvert isNULL (the default) and themagick package is installed, it will be usedto convert the frames to a GIF movie (or other format if supported). Ifmagick is not installed orconvert isTRUE,movie3d will attemptto use the externalImageMagick program to convert theframes to a movie. The newermagick executable is triedfirst, thenconvert if that fails.Thetype argument will be passed toImageMagick to use as a file extensionto choose the file type.

Finally,convert can be a template for a command toexecute in the standard shell (wildcards are allowed). The template isconverted to a command using
sprintf(convert, fps, frames, movie, type, duration, dir)
For example,convert = TRUEuses the template"magick -delay 1x%d %s*.png %s.%s". All workis done in the directorydir, so paths should not be needed inthe command. (Note thatsprintf does not require allarguments to be used, and supports formats that use them in anarbitrary order.)

Thetop = TRUE default is designed to work around an OpenGL limitation:in some implementations,rgl.snapshot will fail if the windowis not topmost.

As ofrgl version 0.94, thedev argument is not needed: thefunctionf can specify its device, asspin3d does, for example. However, ifdev is specified, it will be selectedas the current device as each update is played.

As ofrgl version 0.95.1476,f can include multiple values in a"subscene"component, andpar3d() will be calledfor each of them.

Value

play3d is called for the side effect of its repeated calls tof.It returnsNULL invisibly.

movie3d is also normally called for the side effectof producing the output movie. It invisibly returns

Author(s)

Duncan Murdoch, based on code by Michael Friendly

See Also

spin3d andpar3dinterp return functions suitable to use asf. Seedemo(flag) for an example that modifies thescene inf.

Examples

open3d()plot3d( cube3d(col = "green") )M <- par3d("userMatrix")if (!rgl.useNULL() && interactive())  play3d( par3dinterp(times = (0:2)*0.5, userMatrix = list(M,                                     rotate3d(M, pi/2, 1, 0, 0),                                     rotate3d(M, pi/2, 0, 1, 0) ) ),         duration = 2 )## Not run: movie3d( spin3d(), duration = 5 )## End(Not run)

Add a widget to play animations

Description

This is a widget that can be put in a web page to allowanimations with or without Shiny.

Usage

playwidget(sceneId, controls,            start = 0, stop = Inf, interval = 0.05, rate = 1,            components = c("Reverse", "Play", "Slower", "Faster",                           "Reset", "Slider", "Label"),            loop = TRUE,            step = 1, labels = NULL,            precision = 3,            elementId = NULL, respondTo = NULL,            reinit = NULL,            buttonLabels = components, pause = "Pause",            height = 40,            ...)

Arguments

sceneId

The HTML id of the RGL scene being controlled,or an object. See the Details below.

controls

A single"rglControl" object, e.g.propertyControl, or a list of several.

start,stop

The starting and stopping values of the animation. Iflabels is suppliedstop will default to stepthrough the labels.

interval

The requested interval (in seconds) between updates. Updatesmay occur at longer intervals.

rate

The number of units of “nominal” time per real worldsecond.

components

Which components should be displayed? See Details below.

loop

When the player reaches the end of the interval,should it loop back to the beginning?

step

Step size in the slider.

labels

Optional labels to use, corresponding to slider steps. Set toNULL for auto-generated labels.

precision

Iflabels=NULL, the precision to use when displayingtimer values.

elementId

The HTML id of the generated widget, containing buttons,slider, etc.

respondTo

The HTML ID of a Shiny input control (e.g. asliderInputcontrol) to respond to.

reinit

A vector of ids that will need re-initialization beforebeing drawn again.

buttonLabels,pause

These are the labels that will be shown on the buttons if they are displayed.pause willbe shown on the"Play" button while playing.

height

The height of the widget in pixels. In a pipe, this is a relative height.

...

Additional arguments to pass totohtmlwidgets::createWidget.

Details

Thecomponents are buttons to control the animation,a slider for manual control, and a label to show the currentvalue. They will be displayed in the order given incomponents. Not all need be included.

The buttons have the following behaviour:

Reverse

Reverse the direction.

Play

Play the animation.

Slower

Decrease the playing speed.

Faster

Increase the playing speed.

Reset

Stop the animation and reset to the start value.

IfrespondTo is used, nocomponents are shown, as it is assumed Shiny (or whatever control is being referenced) will provide the UI components.

ThesceneId component can be anotherplaywidget, arglwidget result, or a result ofhtmltools::tags orhtmltools::tagList. This allows youto use amagrittr-style“pipe” command to join anrglwidget with one or moreplaywidgets. If aplaywidget comesfirst,sceneId should be set toNA. Iftherglwidget does not come first,previous values should be piped into itscontrollersargument. Other HTML code (including other widgets)can be used in the chain if wrapped inhtmltools::tagList.

Each control should inherit from"rglControl". Theycan have the following components in addition to any private ones:

labels

default labels for the slider.

param

values to include on the slider.

dependencies

additional HTML dependencies toinclude, after the defaultrglwidgetClass.

Value

A widget suitable for use in anRmarkdown-generated webpage, or elsewhere.

Appearance

The appearance of the controls is set by the stylesheetinsystem.file("htmlwidgets/lib/rglClass/rgl.css").

The overall widget is of classrglPlayer, with idset according toelementId.

The buttons are of HTML classrgl-button, theslider is of classrgl-slider, and the label is ofclassrgl-label. Each element has an id prefixedby the widget id, e.g.elementId-button-Reverse,elementId-slider, etc. (whereelementIdshould be replaced by the actual id).

Thereinit parameter handles the case wherean object needs re-initialization after each change. Forexample, plane objects may need this if their intersectionwith the bounding box changes shape. Note thatre-initialization is generally incompatible withthevertexControl as it modifies valueswhich are set during initialization.

Author(s)

Duncan Murdoch

See Also

subsetControl,propertyControl,ageControl andvertexControl are possible controls to use.

toggleWidget is a wrapper forplaywidget andsubsetControlto insert a single button to toggle some elements in a display.

Examples

saveopts <- options(rgl.useNULL = TRUE)objid <- plot3d(1:10, 1:10, rnorm(10), col=c("red", "red"), type = "s")["data"]control <- ageControl(value=0,             births=1:10,             ages = c(-5,0,5),             colors = c("green", "yellow", "red"),             objids = objid)# This example uses explicit namesrglwidget(elementId = "theplot", controllers = "theplayer",          height = 300, width = 300)playwidget("theplot", control, start = -5, stop = 5,           rate = 3, elementId = "theplayer",           components = c("Play", "Slider"))# This example uses pipes, and can skip the nameswidget <- rglwidget(height = 300, width = 300) %>%playwidget(control, start = -5, stop = 5,           rate = 3, components = c("Play", "Slider"))if (interactive() || in_pkgdown_example())  widgetoptions(saveopts)

3D scatterplot

Description

Draws a 3D scatterplot.

Usage

plot3d(x, ...)## Default S3 method:plot3d(x, y, z,  xlab, ylab, zlab, type = "p", col, size, lwd, radius,add = FALSE, aspect = !add, xlim = NULL, ylim = NULL, zlim = NULL, forceClipregion = FALSE, decorate = !add, ...)## S3 method for class 'mesh3d'plot3d(x, xlab = "x", ylab = "y", zlab = "z", type = c("shade", "wire", "dots"),add = FALSE, aspect = !add, ...)

Arguments

x,y,z

vectors of points to be plotted. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

xlab,ylab,zlab

labels for the coordinates.

type

For the default method, a single character indicating the type of item to plot. Supported types are: 'p' for points, 's' for spheres, 'l' for lines, 'h' for line segments fromz = 0, and 'n' for nothing. For themesh3d method, one of 'shade', 'wire', or 'dots'. Partial matching is used.

col

the color to be used for plotted items.

size

the size for plotted points.

lwd

the line width for plotted items.

radius

the radius of spheres: see Details below.

add

whether to add the points to an existing plot.

aspect

either a logical indicating whether to adjust the aspect ratio, or a new ratio.

xlim,ylim,zlim

If notNULL, set clippinglimits for the plot.

forceClipregion

Force a clipping region to be used,whether or not limits are given.

decorate

Whether to add bounding axes and otherdecorations.

...

additional parameters which will be passed topar3d,material3dordecorate3d.

Details

plot3d is a partial 3D analogue of plot.default.

Missing values in the data are skipped, as in standard graphics.

Ifaspect isTRUE, aspect ratios ofc(1, 1, 1) are passed toaspect3d. IfFALSE, no aspect adjustment is done. In othercases, the value is passed toaspect3d.

Withtype = "s", spheres are drawn centered at the specified locations.The radius may be controlled bysize (specifying the size relativeto the plot display, with the defaultsize = 3 giving a radius about 1/20 of the plot region) orradius (specifying it on the data scaleif an isometric aspect ratio is chosen, or on an average scaleif not).

Value

plot3d is called for the side effect of drawing the plot; a vectorof object IDs is returned.

Clipping

If any ofxlim,ylim orzlim are specified,they should be length two vectors giving lower and upper clipping limits for the corresponding coordinate.NAlimits will be ignored.

If any clipping limits are given, then the data will beplotted in a newly created subscene within the current one;otherwise plotting will take place directly in the currentsubscene. This subscene is named"clipregion"in the results. This may affect the appearance of transparentobjects if some are drawn in theplot3d call and others after, as RGL will not attempt to depth-sort objects if they arein different subscenes. It is best to draw all overlapping transparent objects in the same subscene. See the example inplanes3d. It will also affect the useofclipplanes3d; clipping planes need to be in the same subscene as the objects being clipped.

UseforceClipregion = TRUE to force creation of this subscene even without specifying limits.

Author(s)

Duncan Murdoch

See Also

plot.default,open3d,par3d.There areplot3d.function andplot3d.deldir methods for plotting surfaces.

Examples

  open3d()  x <- sort(rnorm(1000))  y <- rnorm(1000)  z <- rnorm(1000) + atan2(x, y)  plot3d(x, y, z, col = rainbow(1000))

Methods for formulas

Description

These functions provide a simple formula-based interfacetoplot3d andpersp3d.

Usage

## S3 method for class 'formula'plot3d(x, data = NULL, xlab, ylab, zlab, ...)## S3 method for class 'formula'persp3d(x, data = NULL, xlab, ylab, zlab, ...)

Arguments

x

A formula likez ~ x + y.

data

An optional dataframe or list in which to find the componentsof the formula.

xlab,ylab,zlab

Optional axis labels to override the ones automaticallyobtained from the formula.

...

Additional arguments to pass to the defaultplot3dmethod, or thepersp3d method for"deldir"objects.

Details

Only simple formulas (the ones handled by thexyz.coords function) are supported: a single variable on the left hand side (which will be plotted on the Z axis),and a sum of two variables on the right hand side (whichwill be the X and Y axis variables in the plot.)

Value

These functions are called for the side effect of drawingthe plots. Theplot3d method draws a scatterplot. Thepersp3d method draws a surface plot.

Return values are as given by theplot3d.default method or thepersp3d.deldir methods.

Note

Thepersp3d method requires that the suggested packagedeldir is installed.

Author(s)

Duncan Murdoch

Examples

open3d()mfrow3d(1, 2, sharedMouse = TRUE)plot3d(mpg ~ wt + qsec, data = mtcars)if (checkDeldir())  persp3d(mpg ~ wt + qsec, data = mtcars)

Method for plotting simple linear fit

Description

This function provides several plots of the result offitting a two-predictor model.

Usage

## S3 method for class 'lm'plot3d(x,        which = 1,        plane.col = "gray", plane.alpha = 0.5,       sharedMouse = TRUE,        use_surface3d,        do_grid = TRUE,       grid.col = "black",        grid.alpha = 1,       grid.steps = 5,       sub.steps = 4,       vars = get_all_vars(terms(x), x$model),       clip_to_density = 0,       ...)

Arguments

x

An object inheriting from class"lm" obtained by fittinga two-predictor model.

which

Which plot to show? See Details below.

plane.col,plane.alpha

These parameters controlthe colour and transparency of a plane or surface.

sharedMouse

If multiple plots are requested, should they sharemouse controls, so that they move in sync?

use_surface3d

Use thesurface3d function to plot the surfacerather thanplanes3d. This allows curvedsurfaces to be shown. The default isFALSE if the modellooks like a simple 2 parameter linear fit, otherwiseTRUE.

do_grid

Plot a grid.

grid.col,grid.alpha,grid.steps

Characteristics of the grid.

sub.steps

Ifuse_surface3d isTRUE, use an internal grid ofgrid.steps*sub.steps to drawthe surface.sub.steps > 1 allows curvature within facets.Similarly, ifdo_grid isTRUE, it allows curvature within grid lines.

vars

A dataframe containing the variables to plotin the first three columns, with the response assumed to be incolumn 1. See the Note below.

clip_to_density

If positive, the surface, plane or grid will be clipped to a region with sufficient data.

...

Other parameters to pass to the defaultplot3d method, to control the appearance of aspects of the plotother than the plane.

Details

Three plots are possible, depending on the value(s) inwhich:

  1. (default) Show the points and the fitted plane or surface.

  2. Show the residuals and the plane atz = 0.

  3. Show the predicted values on the fitted plane or surface.

Ifclip_to_density is positive, then thesurface, plane or grid will be clipped to the region where a non-parametric density estimate(usingMASS::kde2d), normalized to have amaximum value of 1, is greater than the given value.This will suppress parts of the plot that aren't supported by the observed data.

Value

Called for the side effect of drawing one or more plots.

Invisibly returns a high-level vector of object ids. Names ofobject ids have the plot number (in drawing order) appended.

Note

The default value for thevars argument will handlesimple linear models with a response and two predictors, andsome models with functions of those two predictors. For models that fail (e.g. models usingpoly), youcan include the observed values as in the third example below.

Ifclip_to_density > 0,

  1. The clipping isapproximate, so it may not agree perfectly betweensurfaces, planes and grids.

  2. This option requires the suggested packagesMASS andinterp, and will be ignored witha warning if either is not installed.

Author(s)

Duncan Murdoch

Examples

open3d()ids <- plot3d(lm(mpg ~ wt + qsec, data = mtcars), which = 1:3)names(ids)open3d()plot3d(lm(mpg ~ wt + I(wt^2) + qsec, data = mtcars))open3d()# Specify vars in the order:  response, pred1, pred2.plot3d(lm(mpg ~ poly(wt, 3) + qsec, data = mtcars),        vars = mtcars[,c("mpg", "wt", "qsec")])       open3d()# Clip parts of the plot with few (wt, qsec) pointsplot3d(lm(mpg ~ poly(wt, 3) + qsec, data = mtcars),        vars = mtcars[,c("mpg", "wt", "qsec")],       clip_to_density = 0.1)

Draw text using base graphics math plotting or LaTeX

Description

To plot mathematical text,plotmath3d uses base graphicsfunctions to plot it to a ‘.png’ file, then uses thatfile as a texture in a sprite.latex3d uses thexdvir package to render LaTeX code, then usesthe same approach to display it inrgl.

Usage

plotmath3d(x, y = NULL, z = NULL, text, cex = par3d("cex"),           adj = 0.5, pos = NULL, offset = 0.5,           fixedSize = TRUE, startsize = 480, initCex = 5,            margin = "", floating = FALSE, tag = "",           polygon_offset = material3d("polygon_offset"), ...)latex3d(x, y = NULL, z = NULL, text, cex = par3d("cex"),            adj = 0.5, pos = NULL, offset = 0.5,           fixedSize = TRUE, startsize = 480, initCex = 5,            margin = "", floating = FALSE, tag = "",           polygon_offset = material3d("polygon_offset"),            verbose = FALSE, ...)

Arguments

x,y,z

Coordinates. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

text

A character vector or (inplotmath3d) expression. Seeplotmath for how expressions areinterpreted inplotmath3d. Inlatex3d eachtext entry should be a LaTeX fragment.

cex

Character size expansion.

adj

One value specifying the horizontal adjustment, or two, specifying horizontal and vertical adjustment respectively, or three, for depth as well.

pos,offset

Alternate way to specifyadj; seetext3d

fixedSize

Should the resulting sprite behave like the defaultones, and resize with the scene, or like text, andstay at a fixed size?

startsize,initCex

These parameters are unlikely to be needed by users.startsize is an over-estimate of the size (in pixels) of the largest expression. Increase this if large expressionsare cut off.initCex is the size of text usedto form the bitmap. Increase this if letters look too blurryat the desired size.

margin,floating,tag,polygon_offset

material3d properties for the sprites.

verbose

IfTRUE,latex3d will printintermediate results for debugging.

...

Forplotmath3d, additional arguments to pass totext when drawing the text. Forlatex3d, additional arguments to pass toxdvir::latexGrob.

Value

Called for the side effect of displaying the sprites.The shape ID of the displayed object is returned.

Note

Thetext3d function passes calls toplotmath3d if itsusePlotmath argument isTRUE.This is the default value if itstexts argument looks like an expression.

Thelatex3d function produces nicer looking resultsthanplotmath3d, but it is much slower, especially on the first run.

Author(s)

Duncan Murdoch

See Also

text3d

Examples

open3d()plotmath3d(1:3, 1:3, 1:3, expression(x[1] == 1, x[2] == 2, x[3] == 3))# This lets the text resize with the plottext3d(4, 4, 4, "resizeable text", usePlotmath = TRUE, fixedSize = FALSE)if (requireNamespace("xdvir")) {# Do the same plot using latex3d(). This example runs slowly!    open3d()  latex3d(1:3, 1:3, 1:3, c("$x_1 = 1$", "$x_2 = 2$", "$x_3 = 3$"))  latex3d(4, 4, 4, "resizeable text", fixedSize = FALSE)}

Draw a polygon in three dimensions

Description

This function takes a description of a flat polygon in x, y and z coordinates,and draws it in three dimensions.

Usage

polygon3d(x, y = NULL, z = NULL, fill = TRUE, plot = TRUE,           coords, random = TRUE, ...)

Arguments

x,y,z

Vertices of the polygon in a form accepted byxyz.coords.

fill

logical; should the polygon be filled?

plot

logical; should the polygon be displayed?

coords

Which two coordinates (x = 1,y = 2,z = 3) describe thepolygon. If missing,triangulate makesan automatic choice.

random

Currently ignored. The triangulation is deterministic.

...

Other parameters to pass tolines3d orshade3d ifplot = TRUE.

Details

The function triangulates the two dimensional polygon described bycoords, thenapplies the triangulation to all three coordinates. No check is made that the polygonis actually all in one plane, but the results may be somewhat unpredictable(especially ifrandom = TRUE) if it is not.

Polygons need not be simple; useNA to indicate separate closed pieces. Forfill = FALSE there are no other restrictions on the pieces, but forfill = TRUE the resulting two-dimensional polygon needs to be one thattriangulate can handle.

Value

Ifplot = TRUE, the id number of the lines (forfill = FALSE) or triangles(forfill = TRUE) that have been plotted.

Ifplot = FALSE, then forfill = FALSE, a vector of indices intothe XYZ matrix that could be used to draw the polygon. Forfill = TRUE, a triangular mesh object representing the triangulation.

Author(s)

Duncan Murdoch

See Also

extrude3d for a solid extrusion of a polygon,triangulate forthe triangulation.

Examples

theta <- seq(0, 4*pi, length.out = 50)r <- theta + 1r <- c(r[-50], rev(theta*0.8) + 1)theta <- c(theta[-50], rev(theta))x <- r*cos(theta)y <- r*sin(theta)open3d()plot(x, y, type = "n")polygon(x, y)polygon3d(x, y, x + y, col = "blue")

Add primitive shape

Description

Adds a shape node to the current scene.

Usage

points3d(x, y = NULL, z = NULL,  ...)lines3d(x, y = NULL, z = NULL,  ...)segments3d(x, y = NULL, z = NULL, ...)triangles3d(x, y = NULL, z = NULL, ...)quads3d(x, y = NULL, z = NULL, ...)

Arguments

x,y,z

coordinates. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

...

Material properties (seematerial3d),normals,texcoords orindices; see details below.

Details

The functionspoints3d,lines3d,segments3d,triangles3d andquads3d add points, joined lines, line segments,filled triangles or quadrilaterals to the plots. They correspond to the OpenGL typesGL_POINTS, GL_LINE_STRIP, GL_LINES, GL_TRIANGLES andGL_QUADS respectively.

Points are taken in pairs bysegments3d, triplets as the verticesof the triangles, and quadruplets for the quadrilaterals. Colors are applied vertex by vertex; if different at each end of a line segment, or each vertex of a polygon, the colorsare blended over the extent of the object. Polygonsmust be non-degenerate and quadrilaterals must be entirely in one plane and convex, or the results are undefined.

The appearance of the new objects are defined by the material properties.Seematerial3d for details.

For triangles and quads, the normals at each vertex may be specifiedusingnormals. These may be given in any way that would beacceptable as a single argument toxyz.coords. These need not match the actual normals to the polygon:curved surfaces can be simulated by using other choices of normals.

Texture coordinates may also be specified. These may be given inany way that would be acceptable as a single argument toxy.coords, and are interpreted in termsof the bitmap specified as the material texture, with(0, 0) at the lower left,(1, 1) at the upper right. The textureis used to modulate the color of the polygon.

All of these functions support an argument calledindices, which allows vertices (and other attributes)to be re-used, as they are in objects created bymesh3d and related functions. This isintended to be used on smooth surfaces, where each sharedvertex has just one value for normals, colors and texturecoordinates.

For shapes with flat-looking faces (e.g. polyhedra likecube3d),the verticesmust be duplicatedto be rendered properly.

Value

Each function returns the integer object ID of the shape thatwas added to the scene. These can be passed topop3dto remove the object from the scene.

Author(s)

Ming Chen and Duncan Murdoch

Examples

# Show 12 random vertices in various ways. M <- matrix(rnorm(36), 3, 12, dimnames = list(c('x', 'y', 'z'),                                        rep(LETTERS[1:4], 3)))# Force 4-tuples to be convex in planes so that quads3d works.for (i in c(1, 5, 9)) {    quad <- as.data.frame(M[, i + 0:3])    coeffs <- runif(2, 0, 3)    if (mean(coeffs) < 1) coeffs <- coeffs + 1 - mean(coeffs)    quad$C <- with(quad, coeffs[1]*(B - A) + coeffs[2]*(D - A) + A)    M[, i + 0:3] <- as.matrix(quad)}open3d()# Rows of M are x, y, z coords; transpose to plotM <- t(M)shift <- matrix(c(-3, 3, 0), 12, 3, byrow = TRUE)points3d(M)lines3d(M + shift)segments3d(M + 2*shift)triangles3d(M + 3*shift, col = 'red')quads3d(M + 4*shift, col = 'green')  text3d(M + 5*shift, texts = 1:12)# Add labelsshift <- outer(0:5, shift[1, ])shift[, 1] <- shift[, 1] + 3text3d(shift,        texts = c('points3d', 'lines3d', 'segments3d',         'triangles3d', 'quads3d', 'text3d'),       adj = 0) rgl.bringtotop()

Controls to use with playwidget()

Description

These are setter functions to produce actions in a Shiny app,or in an animation.

Usage

subsetControl(value = 1, subsets, subscenes = NULL,                         fullset = Reduce(union, subsets),                         accumulate = FALSE)propertyControl(value = 0, entries, properties,                 objids = tagged3d(tags), tags, values = NULL,                param = seq_len(NROW(values)) - 1, interp = TRUE)

Arguments

value

The value to use for input (typicallyinput$valuein a Shiny app.)

subsets

A list of vectors of object identifiers; the value willchoose among them.

fullset

Objects in the subscene which are not infullsetwill not be touched.

subscenes

The subscenes to be controlled. IfNULL, theroot subscene.

accumulate

IfTRUE, the subsets will accumulate (by union)as the value increases.

entries,properties,objids

Which properties to set.

tags

Select objects with matching tags. Ignoredifobjids is specified.

values

Values to set.

param

Parameter values corresponding to the rows ofvalue

interp

Whether to use linear interpolation betweenparamvalues

Details

subsetControl produces data forplaywidget todisplay subsets of the object in one or more subscenes. This code will nottouch objects in thesubscenes if theyare not infullset.fullset defaults to the union ofall the object ids mentioned insubsets, so by default if an id isnot mentioned in one of the subsets, it will not be controlled by the slider. Ifvalue is specified in R code, it will be a 1-basedindex into thesubsets list; when specified internallyin Javascript, 0-based indexing into the corresponding arraywill be used.

propertyControl sets individual properties. Here the rowofvalues is determined by the position ofvalueinparam.

Value

These functions return controller data in a list of class"rglControl".

Author(s)

Duncan Murdoch

See Also

subsetSetter for a way to embed a pure Javascriptcontrol, andplaywidget for a way to use thesein animations (including Shiny),rglSharedfor linking using thecrosstalk package. TheUser Interaction in WebGL vignettegives more details.


Generic 3D interface

Description

Generic 3D interface for 3D rendering and computational geometry.

Details

R3d is a design for an interface for 3d rendering and computation without dependencyon a specific rendering implementation. R3d includes a collectionof 3D objects and geometry algorithms.All r3d interface functions are named*3d. They represent generic functions that delegate to implementation functions.

The interface can be grouped into 8 categories: Scene Management, Primitive Shapes,High-level Shapes, Geometry Objects, Visualization, Interaction, Transformation,Subdivision.

The rendering interface gives an abstraction to the underlying rendering model. It canbe grouped into four categories:

Scene Management:

A 3D scene consists of shapes, lights and background environment.

Primitive Shapes:

Generic primitive 3D graphics shapes such as points, lines, triangles, quadrangles and texts.

High-level Shapes:

Generic high-level 3D graphics shapes such as spheres, sprites and terrain.

Interaction:

Generic interface to select points in 3D space using the pointer device.

In this package we include an implementation of r3d using the underlyingrgl.* functions.

3D computation is supported through the use of object structures that live entirely in R.

Geometry Objects:

Geometry and mesh objects allow to define high-level geometry for computational purpose such as triangle or quadrangle meshes (seemesh3d).

Transformation:

Generic interface to transform 3d objects.

Visualization:

Generic rendering of 3d objects such as dotted, wired or shaded.

Computation:

Generic subdivision of 3d objects.

At present, the main practical differences between the r3d functionsand thergl.* functions are as follows.

The r3d functions callopen3d if there is no device open, and thergl.* functions callrgl.open. By defaultopen3d sets the initial orientation of the coordinatesystem in 'world coordinates', i.e. a right-handed coordinate systemin which the x-axis increases from left to right, the y-axisincreases with depth into the scene, and the z-axis increases frombottom to top of the screen.rgl.* functions, on the otherhand, use a right-handed coordinate system similar to that used inOpenGL. The x-axis matches that of r3d, but the y-axis increasesfrom bottom to top, and the z-axis decreases with depth into thescene. Since the user can manipulate the scene, either system canbe rotated into the other one.

The r3d functions also preserve thergl.material setting acrosscalls (except for texture elements, in the current implementation), whereasthe deprecatedrgl.* functions leave it as set by the last call.

The example code below illustrates the two coordinate systems.

See Also

points3d,lines3d,segments3d,triangles3d,quads3d,text3d,spheres3d,sprites3d,terrain3d,select3d,dot3d,wire3d,shade3d,transform3d,rotate3d,subdivision3d,mesh3d,cube3d,rgl

Examples

         x <- c(0, 1, 0, 0)     y <- c(0, 0, 1, 0)     z <- c(0, 0, 0, 1)     labels <- c("Origin", "X", "Y", "Z")     i <- c(1, 2, 1, 3, 1, 4)     # *3d interface          open3d()     text3d(x, y, z, labels)     text3d(1, 1, 1, "*3d coordinates")     segments3d(x[i], y[i], z[i])

Read and write STL (stereolithography) format files

Description

These functions read and write STL files. This is a simple file format thatis commonly used in 3D printing. It does not represent text,only triangles. ThewriteSTL function converts some RGL objecttypes to triangles.

Usage

readSTL(con, ascii = NA, plot = TRUE, ...)writeSTL(con, ascii = FALSE,          pointRadius = 0.005,          pointShape = icosahedron3d(),         lineRadius = pointRadius,         lineSides = 20,         ids = tagged3d(tags),         tags = NULL)

Arguments

con

A connection or filename.

ascii

Whether to use the ASCII format or the binary format. ThedefaultNA setting forreadSTL() causes itto detect the format. This only works for files, not otherconnections, which default to binary.

plot

On reading, should the object be plotted?

...

If plotting, other parameters to pass totriangles3d

pointRadius,lineRadius

The radius of points and lines relative to the overall scale of the figure.

pointShape

A mesh shape to use for points. It is scaled by thepointRadius.

lineSides

Lines are rendered as cylinders with this many sides.

ids

The identifiers (fromids3d) of theobjects to write. IfNULL, try to write everything.

tags

Alternate way to specifyids. Ignored ifids isgiven.

Details

The current implementation is limited. For reading, it ignores normalsand color information. For writing, it only outputs triangles, quads, planes, spheres,points, line segments, line strips and surfaces, and does not write color information.Lines and points are rendered in an isometric scale: if your data scales vary, theywill look strange.

Since the STL format only allows one object per file, all RGL objectsare combined into a single object when output.

The output file is readable by Blender and Meshlab; the latter can write ina number of other formats, including U3D, suitable for import into a PDF document.

Value

readSTL invisibly returns the object id ifplot = TRUE, or (visibly) a matrix of vertices of the triangles if not.

writeSTL invisibly returns the name of the connection to which the data was written.

Author(s)

Duncan Murdoch

References

The file format was found on Wikipedia on October 25, 2012. I learnedabout the STL file format from David Smith's blog reporting on Ian Walker'sr2stl function.

See Also

scene3d saves a copy of a scene to an R variable;rglwidget,writeASY,writePLY,writeOBJ andwriteSTLwrite the scene to a file in various other formats.

Examples

filename <- tempfile(fileext = ".stl")open3d()shade3d( icosahedron3d(col = "magenta") )writeSTL(filename)open3d()readSTL(filename, col = "red")

Defunct functions inrgl

Description

These functions have been removed fromrgl.

Usage

# Removed in version 1.0.0:subsetSlider(subsets, labels = names(subsets),              fullset = Reduce(union, subsets),             subscenes = currentSubscene3d(), prefixes = "",             accumulate = FALSE, ...)             subsetSetter(subsets, subscenes = currentSubscene3d(), prefixes = "",  fullset = Reduce(union, subsets),                         accumulate = FALSE)             clipplaneSlider(a=NULL, b=NULL, c=NULL, d=NULL,                 plane = 1, clipplaneids, prefixes = "",                 labels = signif(values[,1],3), ...)             toggleButton(subset, subscenes = currentSubscene3d(), prefixes = "",              label = deparse(substitute(subset)),              id = paste0(basename(tempfile("input"))), name = id) propertySlider(setter = propertySetter,             minS = NULL, maxS = NULL, step = 1, init = NULL,      labels,      id = basename(tempfile("input")), name = id,     outputid = paste0(id, "text"),     index = NULL,     ...)      propertySetter(values = NULL, entries, properties, objids, prefixes = "",               param = seq_len(NROW(values)), interp = TRUE, digits = 7)                par3dinterpSetter(fn, from, to, steps, subscene, omitConstant = TRUE,                   rename = character(), ...)matrixSetter(fns, from, to, steps, subscene = currentSubscene3d(),              matrix = "userMatrix", omitConstant = TRUE, prefix = "", ...)              vertexSetter(values, vertices = 1, attributes, objid, prefix = "",     param = seq_len(NROW(values)), interp = TRUE,     digits = 7)

See Also

Defunct


Deprecated functions inrgl

Description

These functions are provided for compatibility with older versions ofrgl only, and may be defunct as soon as the next release. See the comments for the replacements.

Usage

rgl.bbox(xat = NULL, xlab = NULL, xunit = 0, xlen = 5,          yat = NULL, ylab = NULL, yunit = 0, ylen = 5,          zat = NULL, zlab = NULL, zunit = 0, zlen = 5,          marklen = 15, marklen.rel = TRUE,          expand = 1, draw_front = FALSE, ...)  # bbox3drgl.bg( sphere = FALSE, fogtype = "none", color = c("black", "white"), back = "lines", fogScale = 1, ...)           # bg3drgl.clear( type = "shapes", subscene = 0 )     # clear3drgl.close()                                    # close3drgl.light( theta = 0, phi = 0, viewpoint.rel = TRUE,            ambient = "#FFFFFF", diffuse = "#FFFFFF", specular = "#FFFFFF",            x = NULL, y = NULL, z = NULL)       # light3drgl.lines(x, y = NULL, z = NULL, ... )         # segments3drgl.linestrips(x, y = NULL, z = NULL, ...)     # lines3drgl.open(useNULL = rgl.useNULL())              # open3drgl.points(x, y = NULL, z = NULL, ... )        # points3drgl.primitive(...)                             rgl.quads(x, y = NULL, z = NULL,           normals = NULL,           texcoords = NULL, ... )              # quads3drgl.select3d(button = c("left", "middle", "right"),            dev = cur3d(),             subscene = currentSubscene3d(dev)) # select3drgl.set(which, silent = FALSE)                 # set3drgl.setAxisCallback(axis, draw = NULL,             dev = cur3d(),             subscene = currentSubscene3d(dev)) # setAxisCallbackrgl.surface(x, z, y, coords = 1:3, ...,             normal_x = NULL, normal_y = NULL, normal_z = NULL,            texture_s = NULL, texture_t = NULL) # surface3drgl.texts(x, y = NULL, z = NULL, text,           adj = 0.5, pos = NULL, offset = 0.5,           family = par3d("family"),           font = par3d("font"),           cex = par3d("cex"),           useFreeType = par3d("useFreeType"),           ...)                                  # text3drgl.triangles(x, y = NULL, z = NULL,               normals = NULL, texcoords = NULL,               ... )                             # triangles3drgl.viewpoint( theta = 0, phi = 15,                fov = 60, zoom = 1,                scale = par3d("scale"),                interactive = TRUE,                userMatrix,                type = c("userviewpoint",                        "modelviewpoint") )     # view3dwriteWebGL(dir = "webGL",            filename = file.path(dir, "index.html"),            template = system.file(file.path("WebGL", "template.html"), package = "rgl"),           prefix = "",           snapshot = TRUE,            commonParts = TRUE,            reuse = NULL,            font = "Arial",            width, height)                       # rglwidget

See Also

Deprecated,bbox3d,bg3d,clear3d,close3d,light3d,lines3d,open3d,points3d,quads3d,rglwidget,segments3d,select3d,set3d,surface3d,text3d,triangles3d,view3d


Duplicated functions inrgl

Description

These functions are provided for compatibility with older versions ofrgl. See the functions in the comments for the full documentation.

Usage

rgl.cur()                             # cur3d      rgl.ids(type = "shapes",         subscene = NA, tags = FALSE)  # ids3d rgl.pop(type = "shapes",         id = 0, tag = NULL)           # pop3dterrain3d(x, y = NULL, z = NULL, ...,          normal_x = NULL, normal_y = NULL, normal_z = NULL,          texture_s = NULL, texture_t=NULL,          flip = FALSE)               # surface3d

See Also

cur3d,ids3d,pop3d,surface3d


Internal RGL functions and data

Description

Internal RGL functions

Usage

rgl.bool(x)rgl.numeric(x)rgl.vertex(x, y = NULL, z = NULL)rgl.nvertex(vertex)rgl.color(color)rgl.mcolor(colors)rgl.clamp(value, low, high)rgl.attr(vattr, nvertex) rgl.enum(name, ..., multi = FALSE)rgl.enum.gl2ps(postscripttype) rgl.enum.nodetype(type)rgl.enum.pixfmt(fmt)rgl.enum.polymode(mode)rgl.enum.textype(textype)rgl.enum.fogtype(fogtype)rgl.enum.primtype(primtype)rgl.enum.texmagfilter(magfiltertype)rgl.enum.texminfilter(minfiltertype)rgl.selectstate(dev, subscene)rgl.setselectstate(state, dev, subscene)edgemap(size)edgeindex(from, to, size, row, col)

Details

These are not to be called by the user.


Integrating RGL with Sweave

Description

As ofR 2.13.0, it is possible to include RGL graphics intoaSweave document. These functions support thatintegration.

Usage

Sweave.snapshot()rgl.Sweave(name, width, height, options, ...)rgl.Sweave.off()

Arguments

name,width,height,options,...

These arguments are passed bySweave torgl.Sweavewhen it opens the device.

Details

Thergl.Sweave function is not normally called by the user. The userspecifies it as the graphics driver when opening the code chunk, e.g. byusing

<<fig = TRUE, pdf = FALSE, grdevice = rgl.Sweave, resolution = 100>>=

When the RGL device is closed at the end of the code chunk,rgl.Sweave.off() will be called automatically. Itwill save a snapshotof the last image (by default in ‘.png’ format) for inclusion in the Sweave document and (by default) close the device. Alternatively, theSweave.snapshot() functioncan be called to save the image before the end of the chunk. Only onesnapshot will be taken per chunk.

Several chunk options are used by thergl.Sweave device:

stayopen

(defaultFALSE). IfTRUE then the RGLdevice willnot be closed at the end of the chunk,instead a call toSweave.snapshot()will be used if it has not been called explicitly. Subsequent chunks can addto the scene.

outputtype

(defaultpng). The output may be specified asoutputtype = pdf oroutputtype = eps instead, in which casethergl.postscript function will be used to write output in thespecified format. Note thatrgl.postscript has limitationsand does not always render scenes correctly.

delay

(default 0.1). After creating the display window,Sys.sleepwill be called to delay this many seconds, to allow the display system to initialize. This is needed in X11 systems which open the displayasynchronously. If the default time is too short,rgl.Sweave mayfalsely report that the window is too large to open.

Value

These functions are called for their side effects.

Note

We recommend turning off all other graphics drivers in a chunk that usesgrdevice = rgl.Sweave. The RGL functions do not write toa standard graphics device.

Note

Thergl package relies on your graphics hardware to render OpenGL scenes,and the default ‘.png’ output copies a bitmap from the hardware device. All such devices have limitations on the size of the bitmap, but they do not always signal these limitations in a way that RGL will detect. If you findthat images are not being produced properly, try reducing the size using theresolution,width orheight chunk options.

Author(s)

Duncan Murdoch

See Also

RweaveLatex for a description of alternate graphics driversin Sweave, and standard options that can be used in code chunks.

hook_rglandhook_webgl allow fixed or interactive RGLscenes to be embedded inknitr documents.


Get information about shapes

Description

Retrieves information about the shapes in a scene.

Usage

rgl.attrib(id, attrib, first = 1, last = rgl.attrib.count(id, attrib))

Arguments

id

A shape identifier, as returned byids3d.

attrib

An attribute of a shape. Currently supported: one of
"vertices","normals","colors","texcoords","dim","texts","cex","adj","radii","centers","ids","usermatrix","types","flags","offsets","family","font","pos"
or unique prefixesto one of those.

first,last

Specify these to retrieve only those rows of the result.

Details

If the identifier is not found or is not a shape that has the given attribute, zero will be returned byrgl.attrib.count, and an empty matrixwill be returned byrgl.attrib.

The first fourattrib names correspond to the usual OpenGLproperties;"dim" is used just for surfaces, defining the rowsand columns in the rectangular grid;"cex","adj","family","font" and"pos" apply only to text objects.

Value

rgl.attribreturns the values of the attribute. Attributesare mostly real-valued, with the following sizes:

"vertices" 3 values x, y, z
"normals" 3 values x, y, z
"centers" 3 values x, y, z
"colors" 4 values r, g, b, a
"texcoords" 2 values s, t
"dim" 2 values r, c
"cex" 1 value cex
"adj" 2 values x, y
"radii" 1 value r
"ids" 1 value id
"usermatrix" 4 values x, y, z, w
"texts" 1 value text
"types" 1 value type
"flags" 1 value flag
"family" 1 value family
"font" 1 value font
"pos" 1 value pos

The"texts","types" and"family"attributes are character-valued; the"flags"attribute is logical valued, with named rows.

These are returned as matrices with the row count equal to the count for the attribute,and the columns as listed above.

Author(s)

Duncan Murdoch

See Also

ids3d,rgl.attrib.info

Examples

p <- plot3d(rnorm(100), rnorm(100), rnorm(100), type = "s", col = "red")rgl.attrib(p["data"], "vertices", last = 10)

Get information about attributes of objects

Description

These functions give information about the attributes ofRGL objects.rgl.attrib.info is the more “user-friendly” function;rgl.attrib.count is a lower-level function more likely to be used in programming.

Usage

rgl.attrib.info(id = ids3d("all", 0)$id, attribs = NULL, showAll = FALSE)rgl.attrib.count(id, attrib)

Arguments

id

One or more RGL object ids.

attribs

A character vector of one or more attribute names.

showAll

Should attributes with zero entries be shown?

attrib

A single attribute name.

Details

See the first example below to get the full list of attributenames.

Value

A dataframe containing the following columns:

id

The id of the object.

attrib

The full name of the attribute.

nrow,ncol

The size of matrix that would be returnedbyrgl.attrib for this attribute.

Author(s)

Duncan Murdoch

See Also

rgl.attrib to obtain the attribute values.

Examples

open3d()id <- points3d(rnorm(100), rnorm(100), rnorm(100), col = "green")rgl.attrib.info(id, showAll = TRUE)rgl.attrib.count(id, "vertices")merge(rgl.attrib.info(), ids3d("all"))

Assign focus to an RGL window

Description

'rgl.bringtotop' brings the current RGL window to thefront of the window stack (and gives it focus).

Usage

rgl.bringtotop(stay = FALSE)

Arguments

stay

whether to make the window stay on top.

Details

Ifstay isTRUE, then the window will stay on topof normal windows.

Note

not completely implemented for X11 graphics (stay not implemented;window managers such as KDE may block this action(set "Focus stealing prevention level" to None in Control Center/Window Behavior/Advanced)).Not currently implemented under OS/X.

Author(s)

Ming Chen/Duncan Murdoch

Examples

open3d()points3d(rnorm(1000), rnorm(1000), rnorm(1000), color = heat.colors(1000))rgl.bringtotop(stay = TRUE)

Low level functions that should not be called by users.

Description

These functions provide the implementation for various*3d functions designed for users to call.

Usage

rgl.abclines(x, y = NULL, z = NULL, a, b = NULL, c = NULL, ...)rgl.planes(a, b = NULL, c = NULL, d = 0, ...)rgl.clipplanes(a, b = NULL, c = NULL, d = 0)rgl.sprites(x, y = NULL, z = NULL, radius = 1,             shapes = NULL, userMatrix, fixedSize = FALSE,            adj = 0.5, pos = NULL, offset = 0.25,             rotating = FALSE, ...)rgl.spheres(x, y = NULL, z = NULL, radius, fastTransparency = TRUE, ...)

Arguments

x,y,z

Coordinates of points

a,b,c

Coordinates of the direction vectors for the lines,or normals for the planes.

d

Plane offset.

radius

Size of sprites or spheres.

fixedSize,rotating

Fixed size, changing orientation.

fastTransparency

Sphere drawing strategy.

adj,pos,offset

Positioning.

...

Material properties.

Details

See the corresponding*3d function:abclines3d,planes3d,clipplanes3d,sprites3d,spheres3d.


Get user-defined axis labelling callbacks.

Description

This function gets a user-defined axis labelling callback in R.

Usage

rgl.getAxisCallback(axis, dev = cur3d(), subscene = currentSubscene3d(dev))

Arguments

axis

Which axis? Can be value from1:3.

dev,subscene

The RGL device and subscene to work with.

Value

The callback function.

Author(s)

Duncan Murdoch

See Also

setAxisCallbacks towork withrglwidget.


Increment ID

Description

This function is mainly for internal use. It simply increments the internal object ID number and returnsthe new value. Negative values have no effect.

Usage

rgl.incrementID(n = 1L)

Arguments

n

An integer increment to use.

Value

The resulting ID value.

Examples

# Get the current ID valuergl.incrementID(0)# Increment itrgl.incrementID()

Initializing RGL

Description

Initializing the RGL system.

Usage

rgl.init(initValue = 0, onlyNULL = FALSE,          debug = getOption("rgl.debug", FALSE))

Arguments

initValue

value for internal use only

onlyNULL

only initialize the null (no display) device

debug

enable some debugging messages

Details

IfuseNULL isTRUE, RGL will use a “null”device. This device records objects as they are plotted, but displays nothing. It is intended for use withrglwidgetand similar functions.

Currentlydebug only controls messages printed by the OpenGLlibrary during initialization. In futuredebug = TRUE maybecome more verbose.

For display within an OpenGL window in R, RGL requires the OpenGLsystem to be installed and available. If there is a problem initializing it, you may see the message⁠'rgl.init' failed, running with 'rgl.useNULL = TRUE'.⁠ Thereare several causes and remedies:

Value

Normally the user doesn't callrgl.init at all: itis called when the package is loaded. It returns nouseful value.


Extract pixel information from window

Description

This function extracts single components of the pixel information from the topmost window.

Usage

rgl.pixels(component = c("red", "green", "blue"),         viewport = par3d("viewport"), top = TRUE)

Arguments

component

Which component(s)?

viewport

Lower left corner and size of desired region.

top

Whether to bring window to top before reading.

Details

The possible components are"red","green","blue","alpha","depth", and"luminance" (the sum of the threecolors). All are scaled from 0 to 1.

Note that the luminance is kept below 1 by truncating the sum; this is the definition used for theGL_LUMINANCE component in OpenGL.

Value

A vector, matrix or array containing the desired components. If one componentis requested, a vector or matrix will be returned depending on the size ofblock requested (length 1 dimensions are dropped); if more, an array, whose last dimensionis the list of components.

Author(s)

Duncan Murdoch

See Also

rgl.snapshot to write a copy to a file,demo("stereo") for functions that make use of this to drawa random dot stereogram and an anaglyph.

Examples

example(surface3d)depth <- rgl.pixels(component = "depth")if (length(depth) && is.matrix(depth)) # Protect against empty or single pixel windows    contour(depth)

Export vector graphics

Description

Saves the screenshot to a file in PostScript or other vector graphics format.

Usage

rgl.postscript( filename, fmt = "eps", drawText = TRUE )

Arguments

filename

full path to filename.

fmt

export format, currently supported: ps, eps, tex, pdf, svg, pgf

drawText

logical, whether to draw text

Details

Animations can be created in a loop modifying the scene and saving a screenshot to a file. (See example below)

This function is a wrapper for the GL2PS library by Christophe Geuzaine,and has the same limitations as that library: not all OpenGL featuresare supported, and some are only supported in some formats.See the reference for full details.

Author(s)

Christophe Geuzaine / Albrecht Gebhardt

References

GL2PS: an OpenGL to PostScript printing library by Christophe Geuzaine,https://www.geuz.org/gl2ps/, version 1.4.2.

See Also

view3d,snapshot3d

Examples

# Create new files in tempdirsavedir <- setwd(tempdir())x <- y <- seq(-10, 10, length.out = 20)z <- outer(x, y, function(x, y) x^2 + y^2)persp3d(x, y, z, col = 'lightblue')title3d("Using LaTeX text", col = 'red', line = 3)rgl.postscript("persp3da.ps", "ps", drawText = FALSE)rgl.postscript("persp3da.pdf", "pdf", drawText = FALSE)rgl.postscript("persp3da.tex", "tex")pop3d()title3d("Using ps/pdf text", col = 'red', line = 3)rgl.postscript("persp3db.ps", "ps")rgl.postscript("persp3db.pdf", "pdf")rgl.postscript("persp3db.tex", "tex", drawText = FALSE)setwd(savedir)## Not run: ## create a series of frames for an animation#open3d()shade3d(oh3d(), color = "red")view3d(0, 20)for (i in 1:45) {  view3d(i, 20)  filename <- paste("pic", formatC(i, digits = 1, flag = "0"), ".eps", sep = "")   rgl.postscript(filename, fmt = "eps")}## End(Not run)

Switch to select mode, and return the mouse position selected

Description

Mostly for internal use, this function temporarilyinstalls a handler on a button of the mouse that will return the mouse coordinates of one click and drag rectangle.

Usage

rgl.select(button = c("left", "middle", "right"),           dev = cur3d(), subscene = currentSubscene3d(dev))

Arguments

button

Which button to use?

dev,subscene

The RGL device and subscene to work with

Value

A vector of four coordinates: the X and Y coordinates of the start and end of thedragged rectangle.

Author(s)

Duncan Murdoch

See Also

select3d, a version that allows the selection region to be used toselect points in the scene.


Report default use of null device

Description

This function checks the"rgl.useNULL" option if present, or theRGL_USE_NULL environment variable if it is not. If the value isTRUE or a string which matches “yes” or “true”in a case-insensitive test,TRUE is returned.

Usage

rgl.useNULL()

Value

A logical value indicating the current default for use of the nulldevice.

Note

This function is checked by the initialization code when thergl packageis loaded. Thus if you want to run RGL on a system where there is nographics support, you should runoptions(rgl.useNULL = TRUE)or set the environment variableRGL_USE_NULL=TRUE *before*callinglibrary(rgl) (or other code that loadsrgl), and it will not fail in its attempt at initialization.

Author(s)

Duncan Murdoch

See Also

open3d andrgl.open.

Examples

rgl.useNULL()

Convert between RGL user and window coordinates

Description

This function converts from 3-dimensional user coordinatesto 3-dimensional window coordinates.

Usage

rgl.user2window(x, y = NULL, z = NULL, projection = rgl.projection())rgl.window2user(x, y = NULL, z = 0, projection = rgl.projection())rgl.projection(dev = cur3d(), subscene = currentSubscene3d(dev))

Arguments

x,y,z

Input coordinates. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

projection

The RGL projection to use

dev,subscene

The RGL device and subscene to work with

Details

These functions convert between user coordinates and window coordinates.

Window coordinates run from 0 to 1 in X, Y, and Z. X runs from 0 on theleft to 1 on the right; Y runs from 0 at the bottom to 1 at the top;Z runs from 0 foremost to 1 in the background. RGL does not currentlydisplay vertices plotted outside of this range, but in normal circumstances will automatically resize thedisplay to show them. In the example below this has been suppressed.

Value

The coordinate conversion functions produce a matrix with columns corresponding to the X, Y, and Z coordinates.

rgl.projection() returns a list containing the following components:

model

the modelview matrix

projection

the projection matrix

viewport

the viewport vector

Seepar3d for more details.

Author(s)

Ming Chen / Duncan Murdoch

See Also

select3d

Examples

open3d()points3d(rnorm(100), rnorm(100), rnorm(100))if (interactive() || !.Platform$OS == "unix") {# Calculate a square in the middle of the display and plot itsquare <- rgl.window2user(c(0.25, 0.25, 0.75, 0.75, 0.25),                           c(0.25, 0.75, 0.75, 0.25, 0.25), 0.5)par3d(ignoreExtent = TRUE)lines3d(square)par3d(ignoreExtent = FALSE)}

Register extra fonts

Description

This function uses theextrafont package to help register system fonts for use withFreeType inrgl.

Usage

rglExtrafonts(..., quiet = TRUE)

Arguments

...

Vectors of fonts to try. See the Details.

quiet

Whether to print information on progress.

Details

Theextrafontpackage collects information oninstalled fonts from the system. When you firstinstallextrafont, or after new fonts have been installed on yoursystem, runextrafont::font_import() to buildits database of system fonts.

Fonts can be installed inrgl usingrglExtrafonts(rglname = familyname) orrglExtrafonts(familyname). In this callfamilyname is a vector of family names to lookfor in theextrafont database usingextrafont::choose_font(familyname); the first one foundwill be registered withrgl. The optional namerglname will also be usable to refer to the font family.

If none of the given family names is found, no changewill be made to the registered fonts inrgl.

During startup,rgl detects whetherextrafontis installed, and if so runs⁠rglExtrafonts(sans = c("Helvetica", "Arial"), serif = c("Times", "Times New Roman"), mono = c("Courier", "Courier New")) ⁠ to attempt to set up the default fonts.

Fonts found byextrafont can also be used insome other graphics devices besidesrgl; seetheextrafont documentationfor details.

Value

Invisibly returns a vector giving thergl nameand the family name for the newly installed font.

Note

Each font in a display needs a uniquergl name;if the associated font for a given name is changed,all previously plotted text will also change.

Currentlyrglwidget displays will not respect the new definitions.

Author(s)

Duncan Murdoch

See Also

text3d,rglFonts

Examples

if (requireNamespace("extrafont") && !in_pkgdown_example()) {    open3d()  text3d(1,1,1, "Default", family = "sans", cex = 2)      # Attempt to register new sans-serif font:  newfamily <- rglExtrafonts(newsans = c("Comic Sans MS", "Impact",                                          "Verdana", "Tahoma"))    text3d(2,2,2, newfamily, family = "newsans", cex = 2)  }

Specify FreeType fonts

Description

Specify FreeType fonts for use inrgl graphics.

Usage

rglFonts(...)

Arguments

...

Device dependent font definitions for use with FreeType.

Details

FreeType fonts are specified using therglFonts function. This functiontakes a vector of four filenames of TrueType font files whichwill be used for the four styles regular, bold, italic and bold italic. Thevector is passed with a name to be used as the family name, e.g.rglFonts(sans = c("/path/to/FreeSans.ttf", ...)). In order to limit the file size, thergl package ships with just 3 font files, for regular versions of theserif,sans andmono families. Additional free font files were available in the past from theAmaya project, though currently therglExtrafonts function provides an easier wayto register new fonts.

On Windows the system fonts are acceptable and are usedwhenuseFreeType = FALSE (the current default inr3dDefaults). Mappings tofamily namesare controlled by thegrDevices::windowsFonts()function.

Full pathnames should normally be used to specify font files. If relativepaths are used, they are interpreted differently by platform. CurrentlyWindows fonts are looked for in the Windows fonts folder, while otherplatforms use the current working directory.

If FreeType fonts are not used, then bitmapped fonts will be used instead.On Windows these will be based on the fonts specified using the

windowsFontsfunction, and are resizable.Other platforms will use the default bitmapped font which is notresizable.

Bitmapped fonts have a limited number of characters supported; if anyunsupported characters are used, an error will be thrown.

Value

the current set of font definitions.

See Also

text3d

Examples

## Not run: # These FreeType fonts are available from the Amaya project, and are not shipped# with rgl.  You would normally install them to the rgl/fonts directory# and use fully qualified pathnames, e.g. # system.file("fonts/FreeSerif.ttf", package = "rgl")rglFonts(serif = c("FreeSerif.ttf", "FreeSerifBold.ttf", "FreeSerifItalic.ttf",                 "FreeSerifBoldItalic.ttf"),         sans  = c("FreeSans.ttf", "FreeSansBold.ttf", "FreeSansOblique.ttf",                 "FreeSansBoldOblique.ttf"),         mono  = c("FreeMono.ttf", "FreeMonoBold.ttf", "FreeMonoOblique.ttf",                 "FreeMonoBoldOblique.ttf"),         symbol= c("ESSTIX10.TTF", "ESSTIX12.TTF", "ESSTIX9_.TTF",                  "ESSTIX11.TTF"))## End(Not run)

RGL id values

Description

All objects in an RGL scene have anumerical id. These ids are normally storedin vectors of classc("rglIds", "numeric"), whichwill also have class"rglHighlevel"or"rglLowlevel" depending on whether a high level function likeplot3d orpersp3d, or a low level function created the objects.

Usage

rglId(ids = integer())lowlevel(ids = integer())highlevel(ids = integer())## S3 method for class 'rglId'print(x,       rglwidget = getOption("rgl.printRglwidget", FALSE),      ...)

Arguments

ids

A vector of object ids.

x

An"rglId" object to print.

rglwidget

Whether to create and print an RGL widget.If false, nothing is printed.

...

Other arguments which will be passed torglwidget if it is used.

Details

These functions and classes are intended to allowRGL scenes to be automatically displayed in R Markdown documents. SeesetupKnitr for details on enabling auto-printing.

Note thatall objects in the currentscene will be printed by default, not justthe ids inx. (One reason for thisis that lights are also objects; printingobjects without lights would rarely makesense.)

Value

Objects of class"rglId",c("rglHighlevel", "rglId","numeric") orc("rglLowlevel", "rglId","numeric") forrglId,lowlevel orhighlevel respectively.

Author(s)

Duncan Murdoch

Examples

x <- matrix(rnorm(30), ncol = 3, dimnames = list(NULL, c("x", "y", "z")))p <- plot3d(x, type = "s")str(p)if (interactive() || in_pkgdown_example())  print(p, rglwidget = TRUE)

Generate HTML code to select mouse mode

Description

This generates an HTMLselect element to choose among the mouse modes supported byrglwidget.

Usage

rglMouse(sceneId,          choices = c("trackball", "selecting",                      "xAxis", "yAxis", "zAxis",                      "polar", "zoom", "fov",                      "none"),          labels = choices,          button = 1,          dev = cur3d(),          subscene = currentSubscene3d(dev),          default = par3d("mouseMode", dev = dev, subscene = subscene)[button + 1],         stayActive = FALSE,         height = 40,         ...)

Arguments

sceneId

Either anrglwidget or theelementIdfrom one of them.

choices

Which mouse modes to support?

labels

How to label each mouse mode.

button

Which mouse button is being controlled.

dev

The RGL device used for defaults.

subscene

Which subscene is being modified.

default

What is the default entry to show in the control.

stayActive

Whether a selection brush should stay active if themouse mode is changed.

height

The (relative) height of the item in the output display.

...

Additional arguments to pass tohtmltools::tags$select(), e.g.id orclass.

Details

A result of anrglwidget call can be passedas thesceneId argument. This allows the widgetto be “piped” into therglMouse call.The widget will appear first, the selector next inatagList.

If thesceneId is a character string, it should betheelementId of a separately constructedrglwidget result.

Finally, thesceneId can be omitted. In this casetherglMouse result needs to be passed into anrglwidget call as part of thecontrollers argument. This will place the selector before thewidget on the resulting display.

If the mouse mode is changed while brushing the scene, by default the brush will be removed (and so the selectionwill be cleared too). If this is not desired, setstayActive = TRUE.

Value

A browsable value to put in a web page.

Author(s)

Duncan Murdoch

See Also

TheUser Interaction in WebGL vignettegives more details.

Examples

if (interactive() || in_pkgdown_example()) {  open3d()  xyz <- matrix(rnorm(300), ncol = 3)  id <- plot3d(xyz, col = "red", type = "s")["data"]  par3d(mouseMode = "selecting")  share <- rglShared(id)# This puts the selector below the widget.  rglwidget(shared = share, width = 300, height = 300) %>% rglMouse()  # This puts the selector above the widget.  rglMouse() %>% rglwidget(shared = share, width = 300, height = 300, controllers = .) }

Create shared data from an RGL object

Description

Thecrosstalk package provides a way fordifferent parts of an interactive display to communicate about datasets, using “shared data” objects. When selection or filteringis performed in one view, the result is mirrored in all other views.

This function allows vertices of RGL objectsto be treated as shared data.

Usage

rglShared(id, key = NULL, group = NULL,          deselectedFade = 0.1,           deselectedColor = NULL,  selectedColor = NULL,          selectedIgnoreNone = TRUE,  filteredFade = 0,          filteredColor = NULL)

Arguments

id

An existing RGL id.

key

Optional unique labels to apply to each vertex.If missing, numerical keys will be used.

group

Optional name of the shared group to whichthis data belongs. If missing, a random namewill be generated.

deselectedFade,deselectedColor

Appearance of points that are not selected. See Details.

selectedColor

Appearance of points that are selected.

selectedIgnoreNone

If no points are selected, should the points be shownin their original colors (TRUE), or in the deselected colors (FALSE)?

filteredFade,filteredColor

Appearance of points that have been filtered out.

Details

Some functions which normally work on dataframe-like datasets will accept shared dataobjects in their place.

If a selection is in progress, the alpha value forunselected points is multiplied bydeselectedFade.IfdeselectedColor isNULL, the color is leftas originally specified; if not, the point is changed tothe color given bydeselectedColor.

If no points have been selected, then by default pointsare shown in their original colors. However, ifselectedIgnoreNone = FALSE, all points are displayedas if unselected.

TheselectedColor argument is similarly used to change the color (or not) of selected points, andfilteredFade andfilteredColor are used for points thathave been filtered out of the display.

Value

An object of class"SharedData" (from the optionalcrosstalk package) which contains the x, y and z coordinates of the RGL object with the givenid.

Author(s)

Duncan Murdoch

References

https://rstudio.github.io/crosstalk/index.html

See Also

TheUser Interaction in WebGL vignettegives more details.

Examples

  save <- options(rgl.useNULL = TRUE)    #  rglShared requires the crosstalk package,  #  and the slider and rglMouse require manipulateWidget    if (requireNamespace("crosstalk", quietly = TRUE) &&      requireNamespace("manipulateWidget", quietly = TRUE)) {    open3d()    x <- sort(rnorm(100))    y <- rnorm(100)    z <- rnorm(100) + atan2(x, y)    ids <- plot3d(x, y, z, col = rainbow(100))    # The data will be selected and filtered, not the axes.    sharedData <- rglShared(ids["data"])      # Also add some labels that are only displayed    # when points are selected      sharedLabel <- rglShared(text3d(x, y, z, text = 1:100,                                    adj = -0.5),                             group = sharedData$groupName(),                             deselectedFade = 0,                             selectedIgnoreNone = FALSE)     if (interactive() || in_pkgdown_example())       crosstalk::filter_slider("x", "x", sharedData, ~x) %>%      rglwidget(shared = list(sharedData, sharedLabel), controller = .) %>%       rglMouse()  }      options(save)

Convert RGL userMatrix to lattice or base angles

Description

These functions take a user orientation matrixfrom an RGL scene and approximate theparameters to eitherlattice or basegraphics functions.

Usage

rglToLattice(rotm = par3d("userMatrix"))rglToBase(rotm = par3d("userMatrix"))

Arguments

rotm

A matrix in homogeneous coordinates to convert.

Details

Thelattice package can use Euler angles inthe ZYX scheme to describe the rotation of a scenein itswireframe orcloud functions. TherglToLattice function computes these anglesbased onrotm, which defaults to the currentuser matrix. This allows RGL to be usedto interactively find a decent viewpoint andthen reproduce it inlattice.

The base graphicspersp function doesnot use full Euler angles; ituses a viewpoint angle, and assume the z axisremains vertical. TherglToBase functioncomputes the viewpoint angle accurately if theRGL scene is displayed with a verticalz axis, and does an approximation otherwise.

Value

rglToLattice returns a list suitable tobe used as thescreen argument towireframe.

rglToBase returns a list containingtheta andphi components whichcan be used as corresponding arguments inpersp.

Author(s)

Duncan Murdoch

Examples

persp3d(volcano, col = "green")if ((hasorientlib <- requireNamespace("orientlib", quietly = TRUE)) &&     requireNamespace("lattice", quietly = TRUE))     lattice::wireframe(volcano, screen = rglToLattice())if (hasorientlib) {  angles <- rglToBase()  persp(volcano, col = "green", border = NA, shade = 0.5,        theta = angles$theta, phi = angles$phi)}

An htmlwidget to hold an RGL scene

Description

Thehtmlwidgets package provides a framework for embeddinggraphical displays in HTML documents of various types. This functionprovides the necessities to embed an RGL scene in one.

Usage

rglwidget(x = scene3d(minimal), width = figWidth(), height = figHeight(),          controllers = NULL,          elementId = NULL,           reuse = FALSE,          webGLoptions = list(preserveDrawingBuffer = TRUE),           shared = NULL, minimal = TRUE,           webgl, snapshot,           shinyBrush = NULL,           altText = "3D plot",          ...,          oldConvertBBox = FALSE,          fastTransparency = getOption("rgl.fastTransparency", TRUE))

Arguments

x

An RGL scene produced by thescene3d function.

width,height

The width and height of the display in pixels.

controllers

Names ofplaywidget objectsassociated with this scene, or objects (typically piped in). See Details below.

snapshot,webgl

Control of mode of display of scene.See Details below.

elementId

The id to use on the HTMLdivcomponent that will hold the scene.

reuse

Ignored. See Details below.

webGLoptions

A list of options to passto WebGL when the drawing context is created. See the Details below.

shared

An object produced byrglShared, or a list of such objects.

minimal

Should attributes be skipped if they currently haveno effect? Seescene3d.

shinyBrush

The name of a Shinyinput elementto receive information about mouse selections.

altText

Text to include for screen-readers or browsersthat don't handle WebGL. See Details below.

oldConvertBBox,fastTransparency

See Details below.

...

Additional argumentsto pass tohtmlwidgets::createWidget.

Details

This produces a WebGL version of an RGL scene using thehtmlwidgetsframework. This allows display of the scene in the RStudio IDE, a browser, anrmarkdown documentor in ashiny app.

options(rgl.printRglwidget = TRUE) will causerglwidget() to be called and displayedwhen the result of an RGL call that changes thescene is printed.

In RMarkdown or in standalone code, you can use amagrittr-style“pipe” command to join anrglwidget with aplaywidget ortoggleWidget. If the control widget comesfirst, it should be piped into thecontrollersargument. If therglwidget comes first, itcan be piped into the first argument ofplaywidget ortoggleWidget.

In earlier versions, thereuse argument let one output scene share data from earlier ones. This is no longer supported.

IfelementId isNULL and we are not in a Shiny app,elementId is set to a random value to facilitate re-useof information.

To save the display to a file, usehtmlwidgets::saveWidget.This requirespandoc to be installed. For a snapshot, you can usehtmltools::save_html(img(src=rglwidget(snapshot=TRUE)), file = ...).

ThewebGLoptions argument is a list which willbe passed when the WebGL context is created. Seethe WebGL 1.0 specification onhttps://registry.khronos.org/webgl/ for possiblesettings. The default inrglwidget differsfrom the WebGL default by settingpreserveDrawingBuffer = TRUE in order to allow other tools to readthe image, but please note that some implementationsof WebGL contain bugs with this setting. We haveattempted to work around them, but may change ourdefault in the future if this proves unsatisfactory.

Thewebgl argument controlswhether a dynamic plot is displayed in HTML. In LaTeXand some other formatsdynamic plots can't bedisplayed, so if thesnapshot argument isTRUE,webgl must beFALSE. (In previous versionsof thergl package, bothwebgl andsnapshot could beTRUE; that hasn't worked for a while and is no longerallowed as of version 0.105.6.)

Thesnapshot argument controls whether a snapshot isdisplayed: it must be!webgl if both are specified.

Prior torgl 0.106.21,rglwidget converted bounding box decorations into separate objects: a box, textfor the labels, segments for the ticks. By default it nowgenerates these in Javascript, allowing axis labels to move asthey do in the display inR. If you prefer the old conversion,setoldConvertBBox = TRUE.

In version 1.3.4, the handling of transparent objects was changed to match thergl device more closely. The newmethod of rendering is quite a bit faster, though sometimes less accurate. To get the older drawing method setfastTransparency = FALSE.

Value

An object of class"htmlwidget" (or"shiny.tag.list"if pipes are used) that will intelligently print itself intoHTML in a variety of contexts including the R console, within R Markdowndocuments, and within Shiny output bindings.

If objects are passed in theshared argument,then the widget will respond to selection and filtering applied to those as shared datasets. SeerglShared for more details and an example.

R Markdown specifics

In an R Markdown document, you would normally callsetupKnitr(autoprint = TRUE) and would not make explicit calls torglwidget(). If you domake such calls, the graphics will be inserted into thedocument.

Inknitr versions greater than 1.42.5,thealtText argument will be ignored and the alternatetext will be set from chunk optionfig.alt orfig.cap as with other graphics.

Shiny specifics

This widget is designed to work with Shiny for interactivedisplays linked to a server running R.

In a Shiny app, there will often be one or moreplaywidget objects in the app, taking input fromthe user. In order to be sure that the initial value of the user controlis reflected in the scene, you should list all players in thecontrollers argument. See the sample application insystem.file("shinyDemo", package = "rglwidget") for an example.

In Shiny, it is possible to find out information about mouse selectionsby specifying the name of aninput item in theshinyBrush argument. For example, withshinyBrush = "brush3d", each changeto the mouse selection will send data toinput$brush3d in anobject of class"rglMouseSelection" with thefollowing components:

subscene

The ID of the subscene where the mouse is selecting.

state

Either"changing" or"inactive".

region

The coordinates of the corners of the selected region in the window,in orderc(x1, y1, x2, y2).

model, proj, view

The model matrix, projection matrix and viewport in effect at that location.

This object can be used as the first argument toselectionFunction3d to produce a test function forwhether a particular location is in the selected region. If the brush becomes inactive, an object containing only thestatefield will be sent, with value"inactive".

Appearance

The appearance of the display is set by the stylesheetinsystem.file("htmlwidgets/lib/rglClass/rgl.css").

The widget is of classrglWebGL, with idset according toelementId. (As of this writing,no special settings are given for classrglWebGL,but you can add your own.)

Author(s)

Duncan Murdoch

See Also

hook_webgl for an earlier approach to this problem.rglwidgetOutput for Shiny details. TheUser Interaction in WebGL vignettegives more details.

Examples

save <- options(rgl.useNULL=TRUE)example("plot3d", "rgl")widget <- rglwidget()if (interactive() || in_pkgdown_example())  widget  if (interactive() && !in_pkgdown_example()) {  # Save it to a file.  This requires pandoc  filename <- tempfile(fileext = ".html")  htmlwidgets::saveWidget(rglwidget(), filename)  browseURL(filename)}options(save)

Close graphics device in a safe way.

Description

Thedev.off function ingrDevices doesn't restorethe previous graphics device when called. This function does.

Usage

safe.dev.off(which = dev.cur(), prev = dev.prev())

Arguments

which

Which device to close.

prev

Which device to set as current after closing.

Details

This function closes devicewhich if it is not device 1,then callsdev.set(prev) if there are any devices stillopen.

Value

The number and name of the new active device. It will not necessarily beprev if that device isn't already open.

Author(s)

Duncan Murdoch

References

https://bugs.r-project.org/show_bug.cgi?id=18604

Examples

# Open a graphics devicedev.new()first <- dev.cur()# Open a second graphics devicedev.new()second <- dev.cur()second# Open another one, and close it using dev.off()dev.new()dev.off()dev.cur() == second # Not the same as second!# Try again with safe.dev.off()dev.set(second)dev.new()safe.dev.off()dev.cur() == second# Close the other two devssafe.dev.off()safe.dev.off()

Scene management

Description

Clear shapes, lights, bbox

Usage

clear3d( type = c("shapes", "bboxdeco", "material"), defaults, subscene = 0 ) pop3d( type = "shapes", id = 0, tag = NULL)ids3d( type = "shapes", subscene = NA, tags = FALSE )

Arguments

type

Select subtype(s):

"shapes"

shape stack

"lights"

light stack

"bboxdeco"

bounding box

"userviewpoint"

user viewpoint

"modelviewpoint"

model viewpoint

"material"

material properties

"background"

scene background

"subscene"

subscene list

"all"

all of the above

defaults

default values to use after clearing

subscene

which subscene to work with.NA means the current one,0 means the whole scene

id

vector of ID numbers of items to remove

tag

overrideid with objects matchingthesetag material properties

tags

logical; whether to returntag column.

Details

RGL holds several lists of objects in each scene. There are lists for shapes, lights, bounding box decorations, subscenes, etc.clear3d clears the specified stack, or restoresthe defaults for the bounding box (not visible) or viewpoint. Withid = 0pop3d removes the last added node on the list (except for subscenes: there itremoves the active subscene). Theid argumentmay be used to specify arbitrary item(s) to remove; ifid != 0, thetype argument is ignored.

clear3d may also be used to clear material propertiesback to their defaults.

clear3d has an optionaldefaults argument, which defaults tor3dDefaults. Only thematerials component of this argumentis currently used byclear3d.

ids3d returns a dataframe containing the IDs in the currently active subsceneby default, or a specified subscene, or ifsubscene = 0, in the wholergl window along with an indicator of their type and iftags = TRUE, thetag value for each.

Note that clearing the light stack leaves the scene in darkness; it should normallybe followed by a call tolight3d.

See Also

rgl,bbox3d,light3d,open3d to open a new window.

Examples

  x <- rnorm(100)  y <- rnorm(100)  z <- rnorm(100)  p <- plot3d(x, y, z, type = 's', tag = "plot")  ids3d()  lines3d(x, y, z)  ids3d(tags = TRUE)  if (interactive() && !rgl.useNULL() && !in_pkgdown_example()) {    readline("Hit enter to change spheres")    pop3d(id = p["data"])    spheres3d(x, y, z, col = "red", radius = 1/5)    box3d()  }

Saves the current scene to a variable, and displays such variables

Description

This function saves a large part of the RGL state associated with the currentwindow to a variable.

Usage

scene3d(minimal = TRUE)## S3 method for class 'rglscene'plot3d(x, add = FALSE, open3dParams = getr3dDefaults(), ...)## S3 method for class 'rglobject'plot3d(x, ...)## S3 method for class 'rglscene'print(x, ...)## S3 method for class 'rglobject'print(x, ...)

Arguments

minimal

Should attributes be skipped if they currently haveno effect? See Details.

x

An object of class"rglscene"

add

Whether to open a new window, or add to the existing one.

open3dParams

Default parameters foropen3d

...

Additional parameters passed toopen3dbyplot3d(..., add = FALSE). These overrideopen3dParams.

Details

The components saved are: thepar3d settings, thematerial3dsettings, thebg3d settings, the lights and the objects in the scene.

In most cases, callingplot3d on that variable willduplicate the scene. (There are likely to be small differences, mostly internal, butsome aspects of the scene are not currently available.) If textures are used,the name of the texture will be saved, rather than the contents of the texture file.

Other than saving the codeto recreate a scene, saving the result ofscene3d to a file will allow it to be reproduced later most accurately. In roughly decreasing order of fidelity,writeWebGL (now deprecated),writePLY,writeOBJ andwriteSTLwrite the scene to a file in formats readable by other software.

Ifminimal = TRUE (the default), then attributes of objectswill not be saved if they currently have no effect onthe display, thereby reducing the file size. Setminimal = FALSE if the scene is intendedto be used in a context where the appearance could be changed. Currently this only affects the inclusion of normals; withminimal = TRUE they areomitted for objects when the material is not lit.

Value

Thescene3d function returns an object of class"rglscene". This is a list with some or all of the components:

material

The results returned from amaterial3d call.

rootSubscene

A list containing information aboutthe main ("root") subscene. This may include:

id

The scene id.

type

"subscene"

par3d

Thepar3d settings for thesubscene.

embeddings

ThesubsceneInfo()$embeddings for the main subscene.

objects

The ids for objects in the subscene.

subscenes

A recursive list of child subscenes.

objects

A list containing the RGL lights, background and objects in the scene.

The objects in theobjects component are of class"rglobject". They are lists containing some or all of thecomponents

id

The RGL identifier of the object in the original scene.

type

A character variable identifying the type of object.

material

Components of the material that differ from the scene material.

vertices,normals,etc.

Any of the attributes of the object retrievable byrgl.attrib.

ignoreExtent

A logical value indicating whether this object contributes to the bounding box.Currently this may differ from the object in the original scene.

objects

Sprites may contain other objects; they will be stored here as a list of"rglobject"s.

Lights in the scene are stored similarly, mixed into theobjects list.

Theplot3d methods invisibly return a vector of RGL object idsthat were plotted. Theprint methods invisibly return theobject that was printed.

Author(s)

Duncan Murdoch

See Also

rglwidget,writePLY,writeOBJ andwriteSTLwrite the scene to a file in various formats.

Examples

open3d()z <- 2 * volcano        # Exaggerate the reliefx <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)persp3d(x, y, z, col = "green3", aspect = "iso")s <- scene3d()# Make it biggers$par3d$windowRect <- 1.5*s$par3d$windowRect# and draw it againplot3d(s)

Make large change to a scene from Shiny

Description

These functions allow Shiny apps to make relatively large changesto a scene, adding and removing objects from it.

Usage

sceneChange(elementId, x = scene3d(minimal),            delete = NULL, add = NULL, replace = NULL,            material = FALSE, rootSubscene = FALSE,            delfromSubscenes = NULL, skipRedraw = FALSE,            minimal = TRUE)registerSceneChange()

Arguments

elementId

The id of the element holding therglClass instance.

x

The new scene to use as a source for objects to add.

delete,add,replace

Object ids to modify in the scene. Thedelete andreplace ids must be present in the old scene in the browser;theadd andreplace ids must be present inx.

material

Logical to indicate whether default material should be updated.

rootSubscene

Logical to indicate whether root subscene should be updated.

delfromSubscenes

A vector of subscene ids that may have been changed bydeletions. By default, all subscenes inx are used,but the objects may be included in subscenes in the browserthat are different.

skipRedraw

IfTRUE, stop the scene from redrawing untilskipRedraw=FALSE is sent. IfNA, don't redraw this time, but don'tchange the state of theskipRedraw flag.

minimal

Seescene3d.

Details

registerSceneChange must be called in the UI componentof a Shiny app to register the"sceneChange" custommessage.

Value

registerSceneChange returns the HTML code to register themessage.

sceneChange returns a list to be used as the"sceneChange"message to change the scene. Useshiny::session$sendCustomMessage to send it.

Author(s)

Duncan Murdoch

See Also

playwidget for a different approach to modifyingscenes that can be much faster, but may be less flexible. TheShiny demo in this package makes use of all of these approaches.

Examples

## Not run: shinyUI(fluidPage(  registerSceneChange(),  actionButton("thebutton", "Change")))shinyServer(function(input, output, session) {  observeEvent(input$thebutton, {    session$sendCustomMessage("sceneChange",      sceneChange("thewidget", delete = deletes, add = adds))  })})## End(Not run)

Select a rectangle in an RGL scene

Description

This function allows the user to use the mouse toselect a region in an RGL scene.

Usage

select3d(button = c("left", "middle", "right"),             dev = cur3d(), subscene = currentSubscene3d(dev))selectionFunction3d(proj, region = proj$region)

Arguments

button

Which button to use for selection.

dev,subscene

The RGL device and subscene to work with

proj

An object returned fromrgl.projectioncontaining details of the current projection.

region

Corners of a rectangular region in the display.

Details

select3d selects 3-dimensional regions by allowing theuser to use a mouse to draw a rectangle showingthe projection of the region onto the screen. It returnsa function which tests points for inclusion in the selected region.

selectionFunction3d constructs such a test function given coordinates and current transformation matrices.

If the scene is later moved or rotated, the selected region will remain the same, though no longer corresponding to a rectangle on the screen.

Value

These return a functionf(x, y, z) which tests whether eachof the points(x, y, z) is in the selected region, returninga logical vector. This function accepts input in a widevariety of formats as it usesxyz.coords to interpret its parameters.

Author(s)

Ming Chen / Duncan Murdoch

See Also

selectpoints3d,locator

Examples

# Allow the user to select some points, and then redraw them# in a different colorif (interactive() && !in_pkgdown_example()) { x <- rnorm(1000) y <- rnorm(1000) z <- rnorm(1000) open3d() points3d(x, y, z) f <- select3d() if (!is.null(f)) {   keep <- f(x, y, z)   pop3d()   points3d(x[keep], y[keep], z[keep], color = 'red')   points3d(x[!keep], y[!keep], z[!keep]) }}

Select points from a scene

Description

This function uses theselect3d function to allow the user to choose apoint or region in the scene, then reports on all the vertices in or near that selection.

Usage

selectpoints3d(objects = ids3d()$id, value = TRUE, closest = TRUE,                multiple = FALSE, ...)

Arguments

objects

A vector of object id values to use for the search.

value

IfTRUE, return the coordinates of the points; otherwise, returntheir indices.

closest

IfTRUE, return the points closest to the selection of no points areexactly within it.

multiple

IfTRUE or a function, do multiple selections. See the Details below.

...

Other parameters to pass toselect3d.

Details

Themultiple argument may be a logical value or a function. If logical, it controls whether multiple selections will be performed. Ifmultiple isFALSE, a single selection will be performed;it might contain multiple points. IfTRUE, multiple selections will occur and the results will be combined into a single matrix.

Ifmultiple is a function, it should take a single argument.This function will be called with the argument set to a matrixcontaining newly added rows to the value, i.e. it will contain coordinates of the newly selected points (ifvalue = TRUE), or the indices of the points (ifvalue =FALSE). It should return a logical value,TRUE to indicatethat selection should continue,FALSE to indicate that itshould stop.

In either case, if multiple selections are being performed, theESC key will stop the process.

Value

Ifvalue isTRUE, a 3-column matrix giving the coordinates of the selected points. All rows in the matrix will be unique even if multiple verticeshave the same coordinates.

Ifvalue isFALSE, a 2-column matrix containing columns:

id

The object id containing the point.

index

The index of the point withinrgl.attrib(id, "vertices").If multiple points have the same coordinates, all indices will be returned.

Note

This function selects points, not areas. For example,if the selection region is in the interior of the triangle, thatwill count as a miss for all of the triangle's vertices.

Author(s)

Duncan Murdoch

See Also

select3d to return a selection function.

Examples

xyz <- cbind(rnorm(20), rnorm(20), rnorm(20))ids <- plot3d( xyz )if (interactive() && !in_pkgdown_example()) {  # Click near a point to select it and put a sphere there.  # Press ESC to quit...  # This version returns coordinates  selectpoints3d(ids["data"],      multiple = function(x) {        spheres3d(x, color = "red", alpha = 0.3, radius = 0.2)        TRUE     })  # This one returns indices  selectpoints3d(ids["data"], value = FALSE,     multiple = function(ids) {        spheres3d(xyz[ids[, "index"], , drop = FALSE], color = "blue",                   alpha = 0.3, radius = 0.2)        TRUE     })}

User-defined axis labelling callbacks.

Description

This function sets user callbacks to construct axes in R orrglwidget displays.

Usage

setAxisCallbacks(axes, fns,                  javascript = NULL,                  subscene = scene$rootSubscene$id,                  scene = scene3d(minimal = FALSE),                  applyToScene = TRUE,                  applyToDev = missing(scene))

Arguments

axes

Which axes? Specify as number in1:3 or letter inc("x", "y", "z").

fns

Function or list of functions or character vector givingnames of functions.

javascript

Optional block of Javascript code to beincluded (at the global level).

subscene

Which subscene do these callbacks apply to?

scene

Which scene?

applyToScene

Should these changes apply to the scene object?

applyToDev

Should these changes apply to the current device?

Details

IfapplyToScene isTRUE, this function adds Javascript callbacks to thescene object. IfapplyToDev isTRUE, it adds Rcallbacks to the current RGL device.

For Javascript, the callbacks are specified as strings; these will beevaluated within the browser in the global context to define the functions, which will then be called with the Javascriptthis object set to the currentrglwidgetClass object.

For R, they may be strings or R functions.

Both options may beTRUE, in which case thecallbacks must be specified as strings which are both valid Javascript and valid R. The usual way todo this is to give just a function name, with thefunction defined elsewhere, as in the Example below.

The functions should have a header of the formfunction(margin). Themargin argumentwill be a string like"x++" indicating which marginwould be chosen by R. If RGL would not choose to draw anyaxis annotations (which happens withrglwidget, thoughnot currently in R itself), only the letter will be passed,e.g."x".

Value

Invisibly returns anrglScene object. Thisobject will record the changes ifapplyToSceneisTRUE.

IfapplyToDev isTRUE, it will also have the side effect of attempting to install thecallbacks.

Author(s)

Duncan Murdoch

See Also

setUserCallbacks for mouse callbacks.

Examples

# Draw arrows instead of tick marks on axesarrowAxis <- local({  ids <- c(NA, NA, NA)  bbox <- c(NA, NA, NA, NA, NA, NA)  function(margin) {    dim <- if (grepl("x", margin)) 1 else           if (grepl("y", margin)) 2 else           3    inds <- 2*dim + (-1):0    range <- par3d("bbox")[inds]    if (!identical(bbox[inds], range)) {      if (!is.na(ids[dim]))        pop3d(id = ids[dim])             bbox[inds] <<- range       center <- mean(range)      from <- mean(c(range[1], center))      to <- mean(c(center, range[2]))      # margin should agree with suggestion, so use "x++" etc.      margin <- gsub("-", "+", margin)      ids[dim] <<- arrow3d(p0 = c(from, 1, 1),                          p1 = c(to, 1, 1),                         n = 4,                         type = "lines",                         margin = margin,                         floating = TRUE)    }  }})# Define the Javascript function with the same name to use in WebGL# Since Javascript won't change the bounding box, this function# doesn't need to do anything.  js <- "window.arrowAxis = function(margin) {} ;"xyz <- matrix(rnorm(60), ncol = 3)plot3d(xyz, xlab = "x", ylab = "y", zlab = "z")setAxisCallbacks(1:3, "arrowAxis", javascript = js)rglwidget()

Set a one-time slowdown on opening standard graphics

Description

This function is mainly for internal use, to work around a bug in macOS Catalina: if base plotting happenstoo quickly after opening RGL and the first call to quartz, R crashes.

This inserts a delay after the first call to open the graphics device. The default isno delay, unless on Catalina with no graphics devicecurrently open but thequartz device setas the default, when a 1 second delay will be added.Use environment variable "RGL_SLOW_DEV = value" to seta different default delay.

It works by changing the value ofoptions("device"),so explicit calls to the device will not be affected.

It is called automatically when thergl package is loaded.

Usage

setGraphicsDelay(delay = Sys.getenv("RGL_SLOW_DEV", 0),                  unixos = "none")

Arguments

delay

Number of seconds for the delay.

unixos

The name of the Unix OS. If set to"Darwin", and the version is 19.0.0 or greater, the default delay ischanged to 1 second.

Value

Called for the side effect of adding the delay to the firstopening of the graphics device.


Set mouse callbacks in R or Javascript code

Description

This function sets user mouse callbacks in R orrglwidget displays.

Usage

setUserCallbacks(button,                  begin = NULL,                  update = NULL,                  end = NULL,                  rotate = NULL,                 javascript = NULL,                  subscene = scene$rootSubscene$id,                 scene = scene3d(minimal = FALSE),                 applyToScene = TRUE,           applyToDev = missing(scene))

Arguments

button

Which button should this callback apply to? Canbe numeric from0:4, or character from"none", "left", "right", "center", "wheel".

begin,update,end,rotate

Functions to call when events occur. See Details.

javascript

Optional block of Javascript code to beincluded (at the global level).

subscene

Which subscene do these callbacks apply to?

scene

Which scene?

applyToScene

Should these changes apply to the scene object?

applyToDev

Should these changes apply to the current device?

Details

IfapplyToScene isTRUE, this function adds Javascript callbacks to thescene object. IfapplyToDev isTRUE, it adds Rcallbacks to the current RGL device.

For Javascript, the callbacks are specified as strings; these will beevaluated within the browser in the global context to define the functions, which will then be called with the Javascriptthis object set to the currentrglwidgetClass object.

For R, they may be strings or R functions.

Both options may beTRUE, in which case thecallbacks must be specified as strings which are both valid Javascript and valid R. The usual way todo this is to give just a function name, with thefunction defined elsewhere, as in the Example below.

Thebegin andupdate functions should be of the formfunction(x, y) { ... }. Theend functionwill be called with no arguments.

Therotate callback can only be set on the mouse wheel. It is called when the mouse wheel is rotated. It should be of the formfunction(away), whereaway will be 1while rotating the wheel “away” from you,and 2 while rotating it towards you. Ifrotateis not set but other callbacks are set on the wheel“button”, then each click of the mouse wheelwill trigger allstart,update, thenend calls in sequence.

Thejavascript argument is an optional block of code which will be evaluated once during the initialization of the widget. It can define functionsand assign them as members of thewindow object,and then the names of those functions can be given in the callback arguments; this allows the callbacksto share information.

Value

Invisibly returns anrglScene object. Thisobject will record the changes ifapplyToSceneisTRUE.

IfapplyToDev isTRUE, it will also have the side effect of attempting to install thecallbacks usingrgl.setMouseCallbacksandrgl.setWheelCallback.

Author(s)

Duncan Murdoch

See Also

setAxisCallbacks for user defined axes.

Examples

  # This example identifies points in both the rgl window and  # in WebGL    verts <- cbind(rnorm(11), rnorm(11), rnorm(11))  idverts <- plot3d(verts, type = "s", col = "blue")["data"]    # Plot some invisible text; the Javascript will move it  idtext <- text3d(verts[1,,drop = FALSE], texts = 1, adj = c(0.5, -1.5), alpha = 0)    # Define the R functions to use within R  fns <- local({    idverts <- idverts    idtext <- idtext    closest <- -1    update <- function(x, y) {      save <- par3d(skipRedraw = TRUE)      on.exit(par3d(save))      rect <- par3d("windowRect")      size <- rect[3:4] - rect[1:2]      x <- x / size[1];      y <- 1 - y / size[2];      verts <- rgl.attrib(idverts, "vertices")      # Put in window coordinates      vw <- rgl.user2window(verts)      dists <- sqrt((x - vw[,1])^2 + (y - vw[,2])^2)      newclosest <- which.min(dists)      if (newclosest != closest) {        if (idtext > 0)          pop3d(id = idtext)        closest <<- newclosest        idtext <<- text3d(verts[closest,,drop = FALSE], texts = closest, adj = c(0.5, -1.5))      }    }    end <- function() {      if (idtext > 0)        pop3d(id = idtext)      closest <<- -1      idtext <<- -1    }    list(rglupdate = update, rglend = end)  })  rglupdate <- fns$rglupdate  rglend <- fns$rglend    # Define the Javascript functions with the same names to use in WebGL  js <-   ' var idverts = %id%, idtext = %idtext%, closest = -1,         subid = %subid%;        window.rglupdate = function(x, y) {        var   obj = this.getObj(idverts), i, newdist, dist = Infinity, pt, newclosest;       x = x/this.canvas.width;       y = y/this.canvas.height;              for (i = 0; i < obj.vertices.length; i++) {         pt = obj.vertices[i].concat(1);         pt = this.user2window(pt, subid);         pt[0] = x - pt[0];         pt[1] = y - pt[1];         pt[2] = 0;         newdist = rglwidgetClass.vlen(pt);         if (newdist < dist) {           dist = newdist;           newclosest = i;         }       }       if (newclosest !== closest) {         closest = newclosest         var text = this.getObj(idtext);         text.vertices[0] = obj.vertices[closest];         text.colors[0][3] = 1; // alpha is here!         text.texts[0] = (closest + 1).toString();         text.initialized = false;         this.drawScene();       }     };     window.rglend = function() {       var text = this.getObj(idtext);       closest = -1;       text.colors[0][3] = 0;       text.initialized = false;       this.drawScene();     }'  js <- sub("%id%", idverts, js)    js <- sub("%subid%", subsceneInfo()$id, js)  js <- sub("%idtext%", idtext, js)      # Install both  setUserCallbacks("left",                    begin = "rglupdate",                    update = "rglupdate",                    end = "rglend",                    javascript = js)  rglwidget()    # This example doesn't affect the rgl window, it only modifies  # the scene object to implement panning    # Define the Javascript functions to use in WebGL  js <-  '  window.subid = %subid%;        window.panbegin = function(x, y) {       var activeSub = this.getObj(subid),           viewport = activeSub.par3d.viewport,           activeModel = this.getObj(this.useid(activeSub.id, "model")),           l = activeModel.par3d.listeners, i;        this.userSave = {x:x, y:y, viewport:viewport,                            cursor:this.canvas.style.cursor};        for (i = 0; i < l.length; i++) {          activeSub = this.getObj(l[i]);          activeSub.userSaveMat = new CanvasMatrix4(activeSub.par3d.userMatrix);        }        this.canvas.style.cursor = "grabbing";     };          window.panupdate = function(x, y) {         var objects = this.scene.objects,            activeSub = this.getObj(subid),            activeModel = this.getObj(this.useid(activeSub.id, "model")),            l = activeModel.par3d.listeners,            viewport = this.userSave.viewport,            par3d, i, zoom;        if (x === this.userSave.x && y === this.userSave.y)          return;        x = (x - this.userSave.x)/this.canvas.width;        y = (y - this.userSave.y)/this.canvas.height;        for (i = 0; i < l.length; i++) {          activeSub = this.getObj(l[i]);          par3d = activeSub.par3d;          /* NB:  The right amount of zoom depends on the scaling of the data                  and the position of the observer.  This might                  need tweaking.          */          zoom = rglwidgetClass.vlen(par3d.observer)*par3d.zoom;          activeSub.par3d.userMatrix.load(objects[l[i]].userSaveMat);          activeSub.par3d.userMatrix.translate(zoom*x, zoom*y, 0);        }        this.drawScene();     };          window.panend = function() {       this.canvas.style.cursor = this.userSave.cursor;     };'js <- sub("%subid%", subsceneInfo()$id, js)scene <- setUserCallbacks("left",                  begin = "panbegin",                  update = "panupdate",                  end = "panend",                  applyToDev = FALSE, javascript = js)rglwidget(scene)

Set user-defined shaders for RGL objects, or getshaders.

Description

setUserShaders sets user-defined shaders (programs written in GLSL)for customized display of RGL objects. Currentlyonly supported in WebGL displays, as the regulardisplays do not support GLSL.getShaders getsthe user defined shader, or if it is not present, theautomatically generated one.

Usage

setUserShaders(ids, vertexShader = NULL, fragmentShader = NULL,                attributes = NULL, uniforms = NULL, textures = NULL,               scene = scene3d(minimal), minimal = TRUE)getShaders(id, scene = scene3d(minimal), minimal = TRUE)

Arguments

ids,id

Which objects should receive the shaders, or which objectshould be queried?

vertexShader,fragmentShader

The vertex and fragment shader source code. IfNULL, theautomatically generated shader will be used instead.

attributes

A named list of “attributes” to attach to each vertex.

uniforms

A named list of “uniforms”.

textures

A named list of textures.

scene

Ascene3d object to work with.

minimal

Seescene3d.

Details

Modern versions of OpenGL work with “shaders”, programs written to run on the graphics processor. Thevertex shader does the calculations to move vertices andset their intrinsic colours. The fragment shadercomputes how each pixel in the display will be shown,taking into account lighting, material properties, etc.(More precisely, it does the computation for each “fragment”; a fragment is a pixel within an object to display.There may be many objects at a particular location, andeach will result in a fragment calculation unless culledby z-buffering or being discarded in some other way.)

Normally the WebGL Javascript code uses the defaultshaders stored insystem.file("htmlwidgets/lib/rglClass/shaders", package = "rgl"). This function allows them to be writtenby hand, for testing new features, hand optimization, etc.The defines used by the default shaders will also be prependedto user shaders, which can use them for customization onan object-by-object basis.

The names used for theattributes,uniformsandtextures should match names in the shadersfor corresponding variables. (The texture names should benames ofuniform sampler2D variables.)

Value

A modified version of thescene.

Note

ThegetShaders function requires theV8 packageto extract auto-generated shaders, since the definesare generated by Javascript code.

Author(s)

Duncan Murdoch

See Also

rglwidget for display of the scene in WebGL.

Examples

open3d()id <- shade3d(octahedron3d(), col = "red")# For each triangle, set weights on the 3 vertices.# This will be replicated to the appropriate size in Javascript.wts <- diag(3)# This leaves out the centres of each facevs <- "  attribute vec3 aPos;  attribute vec4 aCol;  uniform mat4 mvMatrix;  uniform mat4 prMatrix;  varying vec4 vCol;  varying vec4 vPosition;  attribute vec3 aNorm;  uniform mat4 normMatrix;  varying vec3 vNormal;  attribute vec3 wts;  varying vec3 vwts;  void main(void) {    vPosition = mvMatrix * vec4(aPos, 1.);    gl_Position = prMatrix * vPosition;    vCol = aCol;    vNormal = normalize((normMatrix * vec4(aNorm, 1.)).xyz);    vwts = wts;  }"  fs <- "  #ifdef GL_ES  precision highp float;  #endif  varying vec4 vCol; // carries alpha  varying vec4 vPosition;  varying vec3 vNormal;  uniform mat4 mvMatrix;  uniform vec3 emission;  uniform float shininess;  uniform vec3 ambient[NLIGHTS];  uniform vec3 specular[NLIGHTS]; // light*material  uniform vec3 diffuse[NLIGHTS];  uniform vec3 lightDir[NLIGHTS];  uniform bool viewpoint[NLIGHTS];  uniform bool finite[NLIGHTS];  varying vec3 vwts;  uniform vec2 wtrange;  void main(void) {    float minwt = min(vwts.x, min(vwts.y, vwts.z));    if (minwt < wtrange.x || minwt > wtrange.y) discard;    vec3 eye = normalize(-vPosition.xyz);    vec3 lightdir;    vec4 colDiff;    vec3 halfVec;    vec4 lighteffect = vec4(emission, 0.);    vec3 col;    float nDotL;    vec3 n = normalize(vNormal);    n = -faceforward(n, n, eye);    colDiff = vec4(vCol.rgb * diffuse[0], vCol.a);    lightdir = lightDir[0];    if (!viewpoint[0])      lightdir = (mvMatrix * vec4(lightdir, 1.)).xyz;    if (!finite[0]) {      halfVec = normalize(lightdir + eye);    } else {      lightdir = normalize(lightdir - vPosition.xyz);      halfVec = normalize(lightdir + eye);    }    col = ambient[0];    nDotL = dot(n, lightdir);    col = col + max(nDotL, 0.) * colDiff.rgb;    col = col + pow(max(dot(halfVec, n), 0.), shininess) * specular[0];    lighteffect = lighteffect + vec4(col, colDiff.a);    gl_FragColor = lighteffect;  }"x <- setUserShaders(id, vs, fs, attributes = list(wts=wts),                    uniforms = list(wtrange = c(-0.01, 0.15)))if (interactive() || in_pkgdown_example())  rglwidget(x)

Displaying RGL scenes inknitr documents

Description

These functions allow RGL graphics to be embedded inknitrdocuments.

The simplest method is to runsetupKnitr(autoprint = TRUE)early in the document. That way RGL commands act a lotlike base graphics commands: plots will be automatically insertedwhere appropriate, according to thefig.keep chunk option.By default (fig.keep = "high"), only high-level plotsare kept, after low-level changes have been merged into them.See theknitr documentationhttps://yihui.org/knitr/options/#plots for more details.To suppress auto-printing, the RGL callscan be wrapped ininvisible(). Similarly togrid graphics (used bylatticeandggplot2), automatic inclusion requires the objectto be printed: only the last statement in a code blockin braces is automatically printed. Unlike those packages, auto-printing is the only way to get this towork: callingprint explicitly doesn'twork.

Other functions allow embedding either as bitmaps (hook_rgl with format"png"),fixed vector graphics (hook_rgl with format"eps","pdf" or"postscript"), or interactive WebGL graphics (hook_webgl).hook_rglchunk is not normally invoked by the user; it is the hook that supports automatic creation and deletion of RGL scenes.

Usage

setupKnitr(autoprint = FALSE,           rgl.newwindow = autoprint,           rgl.closewindows = autoprint)hook_rgl(before, options, envir)hook_webgl(before, options, envir)hook_rglchunk(before, options, envir)

Arguments

autoprint

If true, RGL commandsautomatically plot (with low level plots suppressed bythe default value of thefig.keep chunk option.)

rgl.newwindow,rgl.closewindows

Default valuesfor theknitr chunk options.

before,options,envir

Standardknitr hook function arguments.

Details

ThesetupKnitr() function needs to be called onceat the start of the document to install theknitr hooks.If it is called twice in the same session the second call will override the first.

The following chunk options are supported:

Value

A string to be embedded into the output, orNULL if calledwhen no output is available.

Note

ThesetupKnitr(autoprint = TRUE) method assumesall printing of RGL objects happens through auto-printing of objects produced by thelowlevelorhighlevel functions. All RGL functions thatproduce graphics do this, but functions in other packages thatcall them may not return values appropriately.

Mixing explicit callstorglwidget with auto-printing is likely to lead to failure of somescenes to display. To avoid this, setoptions(rgl.printRglwidget = FALSE) before using such explicit calls. Similarly,use that option before calling theexample functionin a code chunk if the example prints RGL objects.

Author(s)

Thehook* functions are originally by Yihui Xie in theknitr package; and have been modified byDuncan Murdoch. Some parts of thesetupKnitr functionduplicate source code fromknitr.


Draw 3D mesh objects

Description

Draws 3D mesh objects in full, or just the edges, or just the vertices.

Usage

  dot3d(x, ...)   # draw dots at the vertices of an object  ## S3 method for class 'mesh3d'dot3d(x, ...,                         front = "points", back = "points")  wire3d(x, ...)  # draw a wireframe object  ## S3 method for class 'mesh3d'wire3d(x, ...,                          front = "lines", back = "lines")  shade3d(x, ...) # draw a shaded object  ## S3 method for class 'mesh3d'shade3d(x, override = TRUE,                            meshColor = c("vertices", "edges", "faces", "legacy"),                            texcoords = NULL, ...,                           front = "filled", back = "filled")

Arguments

x

amesh3d object.

...

additional rendering parameters, or fordots3d andwire3d, parameters to passtoshade3d

override

should the parameters specified here override those stored in the object?

meshColor

how should colours be interpreted? See details below

texcoords

texture coordinates at each vertex.

front,back

Material properties for rendering.

Details

ThemeshColor argument controls how material colours and textures are interpreted. This parameterwas added inrgl version 0.100.1 (0.100.27 fordot3d). Possible values are:

"vertices"

Colours and texture coordinates are applied by vertex, in the orderthey appear in thex$vb matrix.

"edges"

Colours are applied to each edge: first to the segments in thex$is matrix, thenthe 3 edges of each triangle in thex$it matrix, then the 4edges of each quad in thex$ib matrix. This modeis only supported if both front and back materials are"lines", and the mesh contains no points.

"faces"

Colours are applied to each objectin the mesh: first to the points, then the segments, triangles and finally quads. The entire whole face (or point orsegment) receives one colour from the specified colours.

"legacy"

Colours and textures are applied in the same wayas inrgl versions earlier than 0.100.1.

Unique partial matches of these values will be recognized.

If colours are specified butmeshColor is notandoptions(rgl.meshColorWarning = TRUE),a warning will be given that theirinterpretation may have changed. In versions 0.100.1 to 0.100.26ofrgl, the defaultwas to give the warning; now the default is for no warning.

Note that since version 0.102.10,meshColor = "edges" is only allowed when drawing lines (thewire3d default), and it may drawedges more than once. In general, if any renderingdraws twice at the same location, which copy is visible depends on the order of drawing and thematerial3d("depth_test")setting.

Whether points, lines or solid faces are drawn isdetermined in 3 steps:

  1. If arguments"front" or"back" arespecified in the call, those are used.

  2. If one or both of those arguments are notspecified, but the material properties are present inthe object, those are used.

  3. If values are not specified in either of thoseplaces,shade3d draws filled surfaces,wire3d draws lines, anddot3d draws points.

Note: For some versions of rgl up to version 0.107.15, rule 2 above was not respected.

Value

dot3d,wire3d, andshade3d are called for their side effectof drawing an object into the scene; they return an object ID (or vector of IDs) invisibly.

Seeprimitives for a discussion of texture coordinates.

See Also

mesh3d,par3d,shapelist3d for multiple shapes

Examples

  # generate a quad mesh object  vertices <- c(      -1.0, -1.0, 0,      1.0, -1.0, 0,      1.0,  1.0, 0,     -1.0,  1.0, 0  )  indices <- c( 1, 2, 3, 4 )    open3d()    wire3d( mesh3d(vertices = vertices, quads = indices) )    # render 4 meshes vertically in the current view  open3d()    bg3d("gray")  l0 <- oh3d(tran = par3d("userMatrix"), color = "green" )  shade3d( translate3d( l0, -6, 0, 0 ))  l1 <- subdivision3d( l0 )  shade3d( translate3d( l1 , -2, 0, 0 ), color = "red", override = FALSE )  l2 <- subdivision3d( l1 )  shade3d( translate3d( l2 , 2, 0, 0 ), color = "red", override = TRUE )  l3 <- subdivision3d( l2 )  shade3d( translate3d( l3 , 6, 0, 0 ), color = "red" )    # render all of the Platonic solids  open3d()  shade3d( translate3d( tetrahedron3d(col = "red"), 0, 0, 0) )  shade3d( translate3d( cube3d(col = "green"), 3, 0, 0) )  shade3d( translate3d( octahedron3d(col = "blue"), 6, 0, 0) )  shade3d( translate3d( dodecahedron3d(col = "cyan"), 9, 0, 0) )  shade3d( translate3d( icosahedron3d(col = "magenta"), 12, 0, 0) )

Project shadows of mesh onto object.

Description

Project a mesh onto a surface in a scene so that it appears to cast a shadow onto the surface.

Usage

shadow3d(obj, mesh, plot = TRUE, up = c(0, 0, 1),         P = projectDown(up), outside = FALSE,         ...)

Arguments

obj

The target object which will show the shadow.

mesh

The mesh which will cast the shadow.

plot

Whether to plot the result.

up

Which direction is “up”?

P

The projection to use for draping, a 4x4 matrix. Seedrape3d for details on howP is used.

outside

Should the function compute and (possibly) plot the regionoutside of the shadow?

...

Other arguments to pass tofilledContour3d,which will do the boundary calculations and plotting.

Details

shadow3d internally constructs a function that is zero on the boundary of the shadow and positive inside, then draws filled contours of that function. Because thefunction is nonlinear, the boundaries will be approximate,with the best approximation resulting from a largevalue offilledContour3d parameterminVertices.

Ifoutside = TRUE, the first color used byfilledContour3d will indicate the insideof the shadow, and the second color will indicate the exterior.

Value

The returned value fromfilledContour3d.

Author(s)

Duncan Murdoch

See Also

drape3d,facing3d

Examples

open3d()obj <- translate3d(scale3d(oh3d(), 0.3, 0.3, 0.3), 0,0,2)shade3d(obj, col = "red")target <- icosahedron3d()# We offset the target using polygon_offset = 1 so that the# shadow on its surface will appear clearly.shade3d(target, col = "white", polygon_offset = 1)# minVertices = 1000 leaves noticeable artifacts on the edges# of the shadow.  A larger value gives a better result, but is# slower.# We use facing3d(target) so the shadow and outside part only # appear on the upper side of the targetshadow3d(facing3d(target), obj, minVertices = 1000, plot=TRUE,         col = c("yellow", "blue"), outside = TRUE)

Create and plot a list of shapes

Description

These functions create and plot a list of shapes.

Usage

shapelist3d(shapes, x = 0, y = NULL, z = NULL, size = 1, matrix = NULL, override = TRUE,             ..., plot = TRUE)

Arguments

shapes

A singleshape3d object, or a list of them.

x,y,z

Translation(s) to apply

size

Scaling(s) to apply

matrix

A single matrix transformation, or a list of them.

override

Whether the material properties should override the ones in the shapes.

...

Material properties to apply.

plot

Whether to plot the result.

Details

shapelist3d is a quick way to create a complex object made up of simpler ones.Each of the argumentsshapes throughoverride may be a vector of values (a list in the case ofshapes ormatrix). All valueswill be recycled to produce a list of shapes as long as the longest of them.

Thexyz.coords function will be used to process thex,y andz arguments, so a matrix may be used asx to specify all three. If a vector is used forx buty orzis missing, default values of0 will be used.

The"shapelist3d" class is simply a list of"shape3d" objects.

Methods fordot3d,wire3d,shade3d,translate3d,scale3d, androtate3dare defined for these objects.

Value

An object of classc("shapelist3d", "shape3d").

Author(s)

Duncan Murdoch

See Also

mesh3d

Examples

open3d() shapelist3d(icosahedron3d(), x = rnorm(10), y = rnorm(10), z = rnorm(10), col = 1:5, size = 0.3)

Functions for integration of RGL widgets intoShiny app

Description

These functions allow an RGL scene to be embeddedin a Shiny app.

Usage

rglwidgetOutput(outputId, width = "512px", height = "512px")renderRglwidget(expr, env = parent.frame(), quoted = FALSE, outputArgs = list())playwidgetOutput(outputId, width = "0px", height = "0px")renderPlaywidget(expr, env = parent.frame(), quoted = FALSE, outputArgs = list())

Arguments

outputId

The name for the control.

width,height

Width and height to display the control.

expr

An R expression returningarglwidget (forrenderRglwidget) or aplaywidget (forrenderPlaywidget) as output.

env

The environment in which to evaluateexpr.

quoted

Is the expression already quoted?

outputArgs

A list containing arguments; see details below.

Details

UserglwidgetOutput orplaywidgetOutput as an outputobject in a Shiny userinterface section; userenderRglwidget orrenderPlaywidgetas the renderfunction in the server section.

In a dynamic R Markdown document withruntime: shiny, you only call the render function, and may optionally passwidthandheight to the output function by putting them ina list inoutputArgs. See the example below.

Value

Used internally by Shiny.

Author(s)

Duncan Murdoch

Examples

## Not run: # This could be used in a dynamic R Markdown document.  See# demo("shinyDemo") and demo("simpleShinyRgl") for Shiny apps.inputPanel(  sliderInput("n", label = "n", min = 10, max = 100, value = 10, step = 10))renderRglwidget({    n <- input$n    try(close3d())    plot3d(rnorm(n), rnorm(n), rnorm(n))    rglwidget()  }, outputArgs = list(width = "auto", height = "300px"))## End(Not run)

Communicate RGL parameters between R and Javascript in Shiny

Description

These functions allow Shiny apps to read and write thepar3dsettings that may have been modified by user interaction in the browser.

Usage

shinyGetPar3d(parameters, session, subscene = currentSubscene3d(cur3d()), tag = "")shinySetPar3d(..., session, subscene = currentSubscene3d(cur3d()))shinyResetBrush(session, brush)

Arguments

parameters

A character vector naming the parameters to get.

session

The Shiny session object.

subscene

The subscene to which the parameters apply. Defaults to the currently active subscene in the R session.

tag

An arbitrary string or value which will be sent as part of theresponse.

...

A number ofname = value pairs to be modified, or asingle named list of parameters. Entries namedtagorsubscene will be ignored.

brush

The name of a Shiny input element corresponding totheshinyBrush argument torglwidget.

Details

Requesting information from the browser is a complicated process.TheshinyGetPar3d function doesn't return the requested value,it just submits a request for the value to be returned later ininput$par3d, a reactive input. No action will resultexcept when a reactive observer depends oninput$par3d.See the example code below.

TheshinySetPar3d function sends a message to the browserasking it to change a particular parameter. The change will bemade immediately, without sending the full scene to the browser,so should be reasonably fast.

Value

These functions are called for their side effects, and don't returnuseful values.

The side effect ofshinyGetPar3d is to causeinput$par3dto be updated sometime later. Besides the requested parameter values,input$par3d willcontain a copy of thesubscene andtag arguments.

The side effect ofshinySetPar3d is to send a message to thebrowser to update its copy of thepar3d parameters immediately.

Note

R and the browser don't maintain a perfect match between the wayparameters are stored internally. The browser version of parameterswill be returned byshinyGetPar3d and should be supplied toshinySetPar3d.

Author(s)

Duncan Murdoch

References

https://shiny.rstudio.com/articles/communicating-with-js.htmldescribes the underlying mechanisms used by these two functions.

See Also

Therglwidget argumentshinySelectionInput allows information about mouse selectionsto be returned to R.

Examples

if (interactive() && !in_pkgdown_example() && requireNamespace("shiny")) {  save <- options(rgl.useNULL = TRUE)  xyz <- matrix(rnorm(300), ncol = 3)  app = shiny::shinyApp(    ui = shiny::bootstrapPage(      shiny::actionButton("redraw", "Redraw"),      rglwidgetOutput("rglPlot")    ),    server = function(input, output, session) {      # This waits until the user to click on the "redraw"       # button, then sends a request for the current userMatrix      shiny::observeEvent(input$redraw, {        shinyGetPar3d("userMatrix", session)      })          # This draws the plot whenever input$par3d changes,      # i.e. whenever a response to the request above is      # received.      output$rglPlot <- renderRglwidget({        if (length(rgl.dev.list())) close3d()        col <- sample(colors(), 1)        plot3d(xyz, col = col, type = "s", main = col)        par3d(userMatrix = input$par3d$userMatrix)        rglwidget()      })    })  shiny::runApp(app)  options(save)}

Draw a 2D plot on a rectangle in a 3D scene

Description

This function uses a bitmap of a standard 2D graphics plotas a texture on a quadrilateral. Default arguments areset up so that it will appear on the face of the boundingbox of the current 3D plot, but optional arguments allowit to be placed anywhere in the scene.

Usage

show2d(expression,   face = "z-", line = 0,   reverse = FALSE, rotate = 0,   x = NULL, y = NULL, z = NULL,   width = 480, height = 480,   filename = NULL,   ignoreExtent = TRUE,   color = "white", specular = "black", lit = FALSE,   texmipmap = TRUE, texminfilter = "linear.mipmap.linear",  expand = 1.03,  texcoords = matrix(c(0, 1, 1, 0, 0, 0, 1, 1), ncol = 2),  ...)

Arguments

expression

Any plotting commands to produce a plot in standard graphics.Ignored iffilename is notNULL.

face

A character string defining which face of the boundingbox to use. See Details below.

line

How far out from the bounding box should the quadrilateralbe placed? Uses same convention asmtext3d:not lines of text, but fraction of the bounding box size.

reverse,rotate

Should the image be reversed or rotated? See Details below.

x,y,z

Specific values to use to overrideface.

width,height

Parameters to pass topng when creating thebitmap. See Details below.

filename

A ‘.png’ file image to use as the texture.

ignoreExtent

Whether the quadrilateral should be ignored when computingthe bounding box of the scene.

color,specular,lit,texmipmap,texminfilter,...

Material properties to use for the quadrilateral.

expand

Amount by which the quadrilateral is expanded outside the bounding box of the data.

texcoords

Coordinates on the image. Lower leftof the bitmap isc(0,0), upper right isc(1,1).

Details

The default arguments are chosen to make it easy to placea 2D image on the face of the bounding box. Ifx,y andz areNULL (the defaults),face will be used as a code for one of thesix faces of the bounding box. The first letter shouldbe"x","y" or"z"; this defines the axis perpendicular to the desired face. If thesecond letter is"-" or is missing, the facewill be chosen to be the face with the lower value on that axis. Any other letter will use the opposite face.

If any ofx,y orz is given, thespecified value will be used to replace the value calculated above. Usually four values should be given, corresponding tothe coordinates of the lower left, lower right, upper rightand upper left of the destination for the image beforereverse androtate are used. Fewer valuescan be used for one or two coordinates;cbindwill be used to put together all 3 coordinates intoa 4 by 3 matrix (which will be returned as an attributeof the result).

The bitmap plot will by default be oriented so that it isproperly oriented when viewed from thedirection of the higher values of the perpendicular coordinate,and its lower left corner is at the lower value of the tworemaining coordinates. The argumentreverse causesthe orientation to be mirrored, androtate causes itto be rotated by multiples of 90 degrees.rotate should be an integer,with0 for no rotation,1 for a 90 degreecounter-clockwise rotation, etc.

Thewidth andheight arguments control the shapeand resolution of the bitmap. The defaults give a squarebitmap, which is appropriate with the usualc(1,1,1)aspect ratios (seeaspect3d). Some tuning may be needed to choose the resolution. The plot will look best whendisplayed at its original size; shrinking it smaller tends to makeit look faded, while expanding it bigger will make it look blurry. Iffilename is given, the width and heightwill be taken from the file, andwidth andheightarguments will be ignored.

Value

Invisibly returns the id value of the quadrilateral,with the following attributes:

value

The value returned byexpression.

xyz

A 4 by 3 matrix giving the coordinates of the cornersas used in plotting.

texcoords

A 4 by 2 matrix giving the texture coordinatesof the image.

filename

The filename for the temporary file holdingthe bitmap image.

Author(s)

Duncan Murdoch

See Also

bgplot3d uses a plot as the background for the window.

Examples

example(plot3d, ask = FALSE)show2d({  par(mar=c(0,0,0,0))  plot(x, y, col = rainbow(1000), axes=FALSE)  })

Export screenshot

Description

Saves the screenshot to a file.

Usage

rgl.snapshot( filename, fmt = "png", top = TRUE )snapshot3d( filename = tempfile(fileext = ".png"),             fmt = "png", top = TRUE,            ..., scene, width = NULL, height = NULL,            webshot = as.logical(Sys.getenv("RGL_USE_WEBSHOT", "TRUE")) )

Arguments

filename

path to file to save.

fmt

image export format, currently supported: png. Ignored ifwebshot = TRUE.

top

whether to callrgl.bringtotop.Ignored ifwebshot = TRUE.

...

arguments to pass towebshot2::webshot

scene

an optional result ofscene3d orrglwidget to plot

width,height

optional specifications of outputsize in pixels

webshot

Use thewebshot2 package to take the snapshot

Details

rgl.snapshot() is a low-level functionthat copies the current RGL window from the screen. Usersshould usually usesnapshot3d() instead; it is more flexible,and (ifwebshot2 is installed) can take images even ifno window is showing, and they can be larger than the physicalscreen. On some systemswebshot2 doesn't work reliably; ifyou findsnapshot3d() failing or taking a very long timeI'd recommend usingsnapshot3d(..., webshot = FALSE). Seethe note below aboutRGL_USE_WEBSHOT to make this the default.

Animations can be created in a loop modifying the scene and saving each screenshot to a file. Various graphics programs (e.g. ImageMagick)can put these together into a single animation. (Seemovie3d orthe example below.)

Value

These functions are mainly called for the side effects. Thefilename of the saved file is returned invisibly.

Note

Whenrgl.useNULL() isTRUE, onlywebshot = TRUEwill produce a snapshot. It requires thewebshot2package and a Chrome browser. If no suitable browser isfound,snapshot3d() will revert torgl.snapshot().To override the automatic search, setenvironment variableCHROMOTE_CHROMEto the path to a suitable browser.

rgl.snapshot works by taking an image from the displayedwindow on-screen.On some systems, the snapshotwill include content from other windows if they cover the active RGLwindow. Settingtop = TRUE (the default) will usergl.bringtotop before the snapshotto avoid this.

There are likely limits to how largewidth andheight can be set based on the display hardware; if theseare exceeded the results are undefined. A typical resultis that the snapshot will still be made but at a smallersize.

There are slight differences between the displays withwebshot = TRUE andwebshot = FALSE, as the former are rendered using WebGL while the latter are renderedusing OpenGL. Often thewebshot = TRUE displayshave better quality, but they are usually slower toproduce, sometimes drastically so.

Set the environmentvariableRGL_USE_WEBSHOT to"FALSE" ifyou wantrgl.snapshot to be used by default.

See Also

movie3d,view3d

Examples

if (interactive() && !in_pkgdown_example()) {  saveopts <- options(rgl.useNULL = TRUE)  plot3d(matrix(rnorm(300), ncol = 3, dimnames = list(NULL, c("x", "y", "z"))),          col = "red")  options(saveopts)  browseURL(snapshot3d())}## Not run: ## create animation#shade3d(oh3d(), color = "red")rgl.bringtotop()view3d(0, 20)olddir <- setwd(tempdir())for (i in 1:45) {  view3d(i, 20)  filename <- paste("pic", formatC(i, digits = 1, flag = "0"), ".png", sep = "")  snapshot3d(filename)}## Now run ImageMagick in tempdir().  Use 'convert' instead of 'magick'## if you have an older version of ImageMagick:##    magick -delay 10 *.png -loop 0 pic.gifsetwd(olddir)## End(Not run)

Add spheres

Description

Adds a sphere set shape node to the scene

Usage

spheres3d(x, y = NULL, z = NULL, radius = 1, fastTransparency = TRUE, ...)

Arguments

x,y,z

Numeric vector of point coordinates corresponding tothe center of each sphere. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

radius

Vector or single value defining the sphere radius/radii

fastTransparency

logical value indicating whetherfast sorting should be used for transparency. See the Details.

...

Material properties. Seematerial3d for details.

Details

If a non-isometric aspect ratio is chosen, these functions will still drawobjects that appear to the viewer to be spheres. Useellipse3d to draw shapes that are spherical in the data scale.

When the scale is not isometric, the radius is measured in an average scale.In this case the bounding box calculation is iterative, since rescaling theplot changes the shape of the spheres in user-coordinates, which changesthe bounding box. Versions ofrgl prior to 0.92.802 did not do this iterative adjustment.

If any coordinate or radius isNA, the sphere is not plotted.

If a texture is used, its bitmap is wrapped around the sphere, with the top edge at the maximum y coordinate, and the left-right edges joined at the maximum in thez coordinate, centred in x.

If thealpha material value of the spheres is less than the default1, they need to be drawn in order fromback to front. WhenfastTransparency isTRUE, this is approximated by sorting the centers and drawingcomplete spheres in that order. This produces acceptableresults in most cases, but artifacts may be visible, especially if theradius values vary, or they intersect other transparent objects. SettingfastTransparency = FALSE will cause the sorting to apply to each of the 480 facets of individual spheres.This is much slower, but may produce betteroutput.

Value

A shape ID of the spheres object is returned.

See Also

material3d,aspect3d for setting non-isometric scales

Examples

open3d()spheres3d(rnorm(10), rnorm(10), rnorm(10),           radius = runif(10), color = rainbow(10))

Create a function to spin a scene at a fixed rate

Description

This creates a function to use withplay3d tospin an RGL scene at a fixed rate.

Usage

spin3d(axis = c(0, 0, 1), rpm = 5,       dev = cur3d(), subscene = par3d("listeners", dev = dev))

Arguments

axis

The desired axis of rotation

rpm

The rotation speed in rotations per minute

dev

Which RGL device to use

subscene

Which subscene to use

Value

A function with headerfunction(time, base = M), whereMis the result ofpar3d("userMatrix") at the time the functionis created. This functioncalculates and returns a list containinguserMatrix updated byspinning the base matrix fortime seconds atrpm revolutions perminute about the specifiedaxis.

Note

Prior torgl version 0.95.1476, thesubscene argument defaulted to thecurrent subscene, and any additional entries wouldbe ignored byplay3d. The currentdefault value ofpar3d("listeners", dev = dev) means that all subscenes that share mouse responses will also share modificationsby this function.

Author(s)

Duncan Murdoch

See Also

play3d to play the animation

Examples

# Spin one objectopen3d()plot3d(oh3d(col = "lightblue", alpha = 0.5))if (!rgl.useNULL()  && interactive())  play3d(spin3d(axis = c(1, 0, 0), rpm = 30), duration = 2)# Show spinning sprites, and rotate the whole viewopen3d()spriteid <- NULLspin1 <- spin3d(rpm = 4.5 ) # the scene spinnerspin2 <- spin3d(rpm = 9 ) # the sprite spinnerf <- function(time) {    par3d(skipRedraw = TRUE) # stops intermediate redraws    on.exit(par3d(skipRedraw = FALSE)) # redraw at the end    pop3d(id = spriteid) # delete the old sprite    cubeid <- shade3d(cube3d(), col = "red")    spriteid <<- sprites3d(0:1, 0:1, 0:1, shape = cubeid,                   userMatrix = spin2(time,                      base = spin1(time)$userMatrix)$userMatrix)    spin1(time)}if (!rgl.useNULL() && interactive())  play3d(f, duration = 2)

Add sprites

Description

Adds a sprite set shape node to the scene.

Usage

sprites3d(x, y = NULL, z = NULL, radius = 1,           shapes = NULL, userMatrix,           fixedSize = FALSE,           adj = 0.5, pos = NULL, offset = 0.25,           rotating = FALSE, ...)          particles3d(x, y = NULL, z = NULL, radius = 1, ...)

Arguments

x,y,z

point coordinates. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

radius

vector or single value defining the sprite radius

shapes

NULL for a simple square, a vector ofidentifiers of shapes in the scene, or a list of such vectors. See Details.

userMatrix

ifshape is notNULL, the transformation matrix for the shapes

fixedSize

should sprites remain at a fixed size,or resize with the scene?

adj,pos,offset

positioning arguments; see Details

rotating

should sprites remain at a fixed orientation, or rotate with the scene?

...

material properties whenshapes = NULL, texture mapping is supported

Details

Simple sprites (used whenshapes isNULL) are 1 by 1 squaresthat are directed towards the viewpoint. Their primary use is forfast (and faked) atmospherical effects, e.g. particles and cloudsusing alpha blended textures. Particles are sprites using an alpha-blended particle texture giving the illusion of clouds and gases. The centre of each square will by default be at thecoordinates given byx, y, z. This may be adjustedusing theadj orpos parameters.

adj andpos are treated similarly to the sameparameters fortext3d.adj has 3entries, for adjustment to thex,y andz coordinates respectively. Forx, a valueof 0 puts the sprite to the right of the specified point,0.5 centers it there, and 1 puts it to the left. The othercoordinates are similar. By default, each value is 0.5 andthe sprites are centered at the points given by(x, y, z).

Thepos parameter overridesadj. It shouldbe an integer or vector of integers (one per point),interpreted as intext3d to position thesprite relative to the(x, y, z) point: 0 is centered on it, 1 is below,2 is to the left, 3 is above, 4 is to the right, 5 is infront, and 6 is behind.offset is thefraction of the sprite size to separate it from the point.

Whenshapes is notNULL, it should be a vector ofidentifiers of objects to plot in the scene (e.g. as returned byplotting functions or byids3d), or a list of such vectors. The referenced objects willbe removed from the scene and duplicated as sprite images in aconstant orientation, as specified byuserMatrix. By default the origin(0, 0, 0) will be plotted at the coordinates given by(x, y, z), perhaps modified byadjorpos.

Ifshapes is a vector all entries in it will be plotted at everylocation. Ifshapes is a list, different shapeswill be plotted at each location. All entries in list entry 1 will be plottedat location 1, all entries in entry 2 at location 2, etc.Entries will be recycled as needed.

TheuserMatrix argument is ignored forshapes = NULL. Forshapes,sprites3d defaults the matrix tor3dDefaults$userMatrix.

If any coordinate isNA, the sprite is not plotted.

The id values of the shapes may be retrieved after plottingusingrgl.attrib(id, "ids"), the associated entryinshapesis retrievable inrgl.attrib(id, "shapenum"), andthe user matrix is retrieved usingrgl.attrib(id, "usermatrix").

Value

These functions are called for the side effect of displaying the sprites.The shape ID of the displayed object is returned.

Note

While any rgl objects can be used as 3D sprites, spheresproduced byspheres3d and other objects thatadapt to the coordinate systemmay not render properly. To plot spheres, construct themas mesh objects as shown in the example.

See Also

material3d,text3d,pch3d

Examples

open3d()particles3d( rnorm(100), rnorm(100), rnorm(100), color = rainbow(100) )# is the same assprites3d( rnorm(100), rnorm(100), rnorm(100), color = rainbow(100),  lit = FALSE, alpha = .2,  textype = "alpha", texture = system.file("textures/particle.png", package = "rgl") )sprites3d( rnorm(10) + 6, rnorm(10), rnorm(10), shape = shade3d(tetrahedron3d(), col = "red") )open3d()# Since the symbols are objects in the scene, they need# to be added to the scene after calling plot3d()plot3d(iris, type = "n")# Use list(...) to apply different symbols to different points.symbols <- list(shade3d(cube3d(), col = "red"),                shade3d(tetrahedron3d(), col = "blue"),                # Construct spheres                shade3d(addNormals(subdivision3d(icosahedron3d(), 2)),                        col = "yellow"))                sprites3d(iris, shape = symbols[iris$Species], radius = 0.1)

Subdivide a mesh

Description

The subdivision surface algorithm divides and refines (deforms) agiven mesh recursively to certain degree (depth).The mesh3d algorithm consists of two stages: divide and deform.The divide step generates for each triangle or quad four new triangles or quads, the deformstep drags the points (refinement step).

Usage

  subdivision3d( x,  ...)  ## S3 method for class 'mesh3d'subdivision3d( x, depth = 1, normalize = FALSE,                deform = TRUE, keepTags = FALSE, ... )  divide.mesh3d(mesh,  vb = mesh$vb,                 ib = mesh$ib, it = mesh$it, is = mesh$is,                keepTags = FALSE)  normalize.mesh3d(mesh)  deform.mesh3d(mesh, vb = mesh$vb, ib = mesh$ib, it = mesh$it,                is = mesh$is)

Arguments

x

3d geometry mesh

mesh

3d geometry mesh

depth

recursion depth

normalize

normalize mesh3d coordinates after division ifdeform isTRUE

deform

deform mesh

keepTags

ifTRUE, add a"tags"component to the output.

is

indices for segments

it

indices for triangular faces

ib

indices for quad faces

vb

matrix of vertices: 4 x n matrix (rows x, y, z, h) or equivalentvector, where h indicates scaling of each plotted quad

...

other arguments (unused)

Details

subdivision3d takesa mesh object and replaces each segment with two new ones, and each triangle or quad with 4 new onesby adding vertices half-way along the edges (and one in thecentre of a quad). The positions of the vertices are deformed so that the resulting surface is smoother than the original. These operations are repeateddepth times.

The other functions do the individual steps of the subdivision.divide.mesh3d adds the extra vertices.deform.mesh3ddoes the smoothing by replacing each vertex with the average of each of its neighbours.normalize.mesh3d normalizes the homogeneous coordinates, by setting the 4th coordinate to 1. (The 4th coordinate is used as aweight in the deform step.)

Value

A modifiedmesh3d object. IfkeepTags isTRUE, it will contain atags component. Fordetails, see theclipMesh3d help topic.

See Also

r3dmesh3d

Examples

  open3d()  shade3d( subdivision3d( cube3d(), depth = 3 ), color = "red", alpha = 0.5 )

Create, select or modify a subscene

Description

This creates a new subscene, or selects one byid value, or adds objects to one.

Usage

newSubscene3d(viewport = "replace",               projection = "replace",               model = "replace",              mouseMode = "inherit",               parent = currentSubscene3d(),               copyLights = TRUE,               copyShapes = FALSE,               copyBBoxDeco = copyShapes,               copyBackground = FALSE, newviewport,              ignoreExtent)currentSubscene3d(dev = cur3d())useSubscene3d(subscene)addToSubscene3d(ids = tagged3d(tags), tags, subscene = currentSubscene3d())delFromSubscene3d(ids = tagged3d(tags), tags, subscene = currentSubscene3d())gc3d(protect = NULL)

Arguments

viewport,projection,model,mouseMode

How should the new subscene be embedded? Possible values arec("inherit", "modify", "replace"). See Details below.

parent

The parent subscene (defaults to the current subscene).

copyLights,copyShapes,copyBBoxDeco,copyBackground

Whether lights, shapes, bounding box decorations and background should be copied to the new subscene.

newviewport

Optionally specify the new subscene's viewport (in pixels).

ignoreExtent

Whether to ignore the subscene's bounding box when calculating the parent boundingbox. Defaults toTRUE ifmodel is not"inherit".

dev

Which RGL device to query for the current subscene.

subscene

Which subscene to use or modify.

ids

A vector of integer object ids to add to the subscene.

tags

Alternate way to specifyids. Ignored ifids isgiven.

protect

Object ids to protect from this garbage collection.

Details

Thergl package allows multiple windows to be open; each one corresponds to a “scene”.Within each scene there are one or more “subscenes”. Each subscene correspondsto a rectangular region in the window, and may have its own projection, transformation and behaviour in response to the mouse.

There is always a current subscene: most graphic operations make changes there, e.g. by addingan object to it.

The scene “owns” objects;addToSubscene3d anddelFromSubscene3d put their ids into or remove them from the list being displayed within a particular subscene.Thegc3d function deletes objects from the scene if they are not visible in anysubscene, unless they are protected by having their id included inprotect.

Theviewport,projection andmodel parameters each have three possible settings:c("inherit", "modify", "replace")."inherit" means that the corresponding valuefrom the parent subscene will be used."replace" means that the new subscene willhave its own value of the value, independent of its parent."modify" means that the child value will be applied first, and then the parent value will be applied. For viewport, thismeans that if the parent viewport is changed, the child will maintain its relative position. Forthe two matrices,"modify" is unlikely to give satisfactory results, but it is availablefor possible use.

ThemouseMode parameter can only be one ofc("inherit", "replace"). Ifit is"inherit", the subscene will use the mousecontrols of the parent, and any change to them willaffect the parent and all children that inherit from it.This is the behaviour that was present beforerglversion 0.100.13. If it is"replace", thenit will receive a copy of the parent mouse controls,but modifications to them will affect only this subscene, not the parent. Note that this is orthogonalto thepar3d("listeners") setting:if another subscene is listed as a listener, it will respondto mouse actions using the same mode as the one receivingthem.

Theviewport parameter controls the rectangular region in which the subscene is displayed.It is specified usingnewviewport (in pixels relative to the whole window), or set to match the parent viewport.

Theprojection parameter controls settings corresponding to the observer. Theseinclude the field of view and the zoom; they also include the position of the observer relative tothe model. Thepar3d("projMatrix") matrix is determined by the projection.

Themodel parameter controls settings corresponding to the model. Mouse rotations affectthe model, as does scaling. Thepar3d("modelMatrix") matrix is determined by these aswell as by the position of the observer (since OpenGL assumes that the observer is at(0, 0, 0) after the MODELVIEW transformation). Only those parts concerning the model areinherited whenmodel specifies inheritance, the observer setting is controlled byprojection.

IfcopyBackground isTRUE, the background of the newly created child willoverwrite anything displayed in the parent subscene, regardless of depth.

Value

If successful, each function returns the object id of the subscene, with the exception ofgc3d, which returns the count of objects which have been deleted, anduseSubscene3d, which returns the previously active subscene id.

Author(s)

Duncan Murdoch and Fang He.

See Also

subsceneInfo for information about a subscene,mfrow3d andlayout3d to set up multiple panes of subscenes.

Examples

# Show the Earth with a cutout by using clipplanes in subsceneslat <- matrix(seq(90, -90, length.out = 50)*pi/180, 50, 50, byrow = TRUE)long <- matrix(seq(-180, 180, length.out = 50)*pi/180, 50, 50)r <- 6378.1 # radius of Earth in kmx <- r*cos(lat)*cos(long)y <- r*cos(lat)*sin(long)z <- r*sin(lat)open3d()obj <- surface3d(x, y, z, col = "white",        texture = system.file("textures/worldsmall.png", package = "rgl"),        specular = "black", axes = FALSE, box = FALSE, xlab = "", ylab = "", zlab = "",       normal_x = x, normal_y = y, normal_z = z)       cols <- c(rep("chocolate4", 4), rep("burlywood1", 4), "darkgoldenrod1")rs <- c(6350, 5639, 4928.5, 4207, 3486,                          (3486 + 2351)/2, 2351, (2351 + 1216)/2, 1216)for (i in seq_along(rs))   obj <- c(obj, spheres3d(0, 0, col = cols[i], radius = rs[i]))  root <- currentSubscene3d()newSubscene3d("inherit", "inherit", "inherit", copyShapes = TRUE, parent = root)clipplanes3d(1, 0, 0, 0)newSubscene3d("inherit", "inherit", "inherit", copyShapes = TRUE, parent = root)clipplanes3d(0, 1, 0, 0)newSubscene3d("inherit", "inherit", "inherit", copyShapes = TRUE, parent = root)clipplanes3d(0, 0, 1, 0)# Now delete the objects from the root subscene, to reveal the clipping planesuseSubscene3d(root)delFromSubscene3d(obj)

Get information on subscenes

Description

This function retrieves information about the tree of subscenes shown in the activewindow.

Usage

subsceneInfo(id = NA, embeddings, recursive = FALSE)

Arguments

id

Which subscene to report on;NA is the current subscene. Set to"root" for the root.

embeddings

Optional new setting for the embeddings for this subscene.

recursive

Whether to report on children recursively.

Details

In RGL, each window contains a tree of “subscenes”, each containing views of a subset of the objects defined in the window.

Rendering in each subscene depends on the viewport, the projection, and the modeltransformation. Each of these characteristics may be inherited from the parent (embedding[i] = "inherit"), may modify the parent (embedding[i] = "modify"),or may replace the parent (embedding[i] == "replace"). All three must bespecified ifembeddings is used.

Value

id

The object id of the subscene

parent

The object id of the parent subscene, if any

children

Ifrecursive, a list of the information for the children,otherwise just their object ids.

embedding

A vector of 3 components describing how this subscene isembedded in its parent.

Author(s)

Duncan Murdoch

See Also

newSubscene3d

Examples

example(plot3d)subsceneInfo()

Add surface

Description

Adds a surface to the current scene. The surface is defined by a matrix defining the height of each grid point and two vectors or matricesdefining the grid.

Usage

surface3d(x, y, z, ...,          normal_x = NULL, normal_y = NULL, normal_z = NULL,         texture_s=NULL, texture_t=NULL, flip = FALSE)

Arguments

x,y,z

vectors or matrices of values. See Details.

...

Material properties. Seematerial3d for details.

normal_x,normal_y,normal_z

matrices giving the coordinates of normals at each grid point

texture_s,texture_t

matrices giving the texture coordinates at eachgrid point

flip

flip definition of “up”

Details

Adds a surface mesh to the current scene. The surface is typically defined by a matrix of height values inz(as inpersp), but any ofx,y, orz may be matrices orvectors, as long as at least one is a matrix. (One historical exception is allowed: if all are vectors butthe length ofz is the product of the lengths ofx andy,z is converted to a matrix.)

Dimensions of all matrices must match.

If any of the coordinates are vectors, they are interpreted as follows:

If the normals are not supplied, they will be calculated automatically basedon neighbouring points.

Texture coordinates run from 0 to 1 over each dimension of the texture bitmap.If texture coordinates are not supplied, they will be calculated to render the texture exactly once over the grid. Values greater than 1 can beused to repeat the texture over the surface.

surface3d always tries to draw the surface with the ‘front’ upwards(typically towards higherz values). This can be used to renderthe top and bottom differently; seematerial3d andthe example below. If you don't like its choice, setflip = TRUE to use the opposition definition.

NA values in the height matrix are not drawn.

See Also

Seepersp3d for a higher level interface.

Examples

## volcano example taken from "persp"#z <- 2 * volcano        # Exaggerate the reliefx <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)zlim <- range(z)zlen <- zlim[2] - zlim[1] + 1colorlut <- terrain.colors(zlen) # height color lookup tablecol <- colorlut[ z - zlim[1] + 1 ] # assign colors to heights for each pointopen3d()surface3d(x, y, z, color = col, back = "lines")

Find tags on rgl objects.

Description

Objects with material properties may have an arbitrarystring set as a tag. This function retrieves the idvalues associated with a given tag, or the tags set on given ids.

Usage

tagged3d(tags = NULL, ids = NULL, full = FALSE, subscene = 0)

Arguments

tags

A vector of tags to use for selection.

ids

A vector of ids to report the tags on.

full

logical; whether to return a dataframe containingid,type,tag,or a vector of ids or tags.

subscene

Where to look: by default, the whole scene is searched.NA restricts the search to the current subscene,or a subscene id can be given.

Details

Exactly one oftags andids must be specified.

Value

A dataframe is constructed with columns

id

item id

type

item type

tag

item tag

matching the specifiedtags orids value.Iffull = TRUE, the full dataframe is returned, otherwisejust the requested ids or tags.

Ifids is specified, the return value will bein the same orderasids).

Author(s)

Duncan Murdoch

Examples

open3d()ids <- plot3d(rnorm(10), rnorm(10), rnorm(10), tag = "plot")unclass(ids)tagged3d("plot")tagged3d(ids = ids, full = TRUE)

Add text to plot

Description

Adds text to the scene. The text is positioned in 3D space. Text is always oriented towards the camera.

Usage

text3d(x, y = NULL, z = NULL, texts, adj = 0.5, pos = NULL, offset = 0.5,       usePlotmath = is.language(texts),        family = par3d("family"), font = par3d("font"),  cex = par3d("cex"), useFreeType = par3d("useFreeType"),...) texts3d(x, y = NULL, z = NULL, texts, adj = 0.5, pos = NULL, offset = 0.5,       usePlotmath = is.language(texts),       family = par3d("family"), font = par3d("font"),  cex = par3d("cex"), useFreeType = par3d("useFreeType"),...)

Arguments

x,y,z

point coordinates. Any reasonable way of defining thecoordinates is acceptable. See the functionxyz.coordsfor details.

texts

text character vector to draw

adj

one value specifying the horizontal adjustment, or two, specifying horizontal and vertical adjustment respectively, or three, specifying adjustment in allthree directions.

pos

a position specifier for the text. If specified, thisoverrides anyadj value given. Values of 0, 1, 2, 3, 4, 5, 6 respectively indicate positions at, below, to the left of, above, to the right of, in front of, and behind the specified coordinates.

offset

whenpos is specified, this value gives the offset of the label from the specified coordinate in fractions of a character width.

usePlotmath

logical. Shouldplotmath3d be used for the text?

family

A device-independent font family name, or ""

font

A numeric font number from 1 to 4

cex

A numeric character expansion value

useFreeType

logical. Should FreeType be used to draw text? (See details below.)

...

Material properties; seematerial3d for details.

Details

Theadj parameter determines the position of the text relative to the specified coordinate. Useadj = c(0, 0) to place the left bottom corner at(x, y, z),adj = c(0.5, 0.5) to center the text there, andadj = c(1, 1)to put the right top corner there. The optional second coordinate for vertical adjustment defaults to0.5. Placement is done using the "advance" ofthe string and the "ascent" of the font relative to the baseline, when these metricsare known.

text3d andtexts3d draw text using ther3dconventions. These are synonyms; the former is singular to beconsistent with the classic 2-D graphics functions, and the latter isplural to be consistent with all the other graphics primitives. Takeyour choice!

If any coordinate or text isNA, that text is not plotted.

IfusePlotmath isTRUE, the work will be doneby theplotmath3d function. This is the defaultif thetextsparameter is “language”, e.g. the result ofa call toexpression orquote.

Value

The text drawing functions return the object ID of the text object (or sprites, in case ofusePlotmath = TRUE)invisibly.

Fonts

Fonts are specified using thefamily,font,cex, anduseFreeType arguments. Defaults for the currently activedevice may be set usingpar3d, or for future devicesusingr3dDefaults.

Thefamily specification is the same as for standard graphics, i.e.families
c("serif", "sans", "mono", "symbol")
are normallyavailable, but users may add additional families.font numbersare restricted to the range 1 to 4 for standard, bold, italic and bold italicrespectively. Font 5 is recoded as family"symbol"font 1, but that is not supported unless specificallyinstalled, so should be avoided.

Using an unrecognized value for"family" will result inthe system standard font as used in RGL up to version 0.76. That fontis not resizable andfont values are ignored.

IfuseFreeType isTRUE, then RGL will use the FreeTypeanti-aliased fonts for drawing. This is generally desirable, and it is thedefault on non-Windows systems if RGL was built to support FreeType.

FreeType fonts are specified using therglFonts function.

See Also

r3d,plotmath3d,rglExtrafonts for adding fonts

Examples

open3d()famnum <- rep(1:3, 8)family <- c("serif", "sans", "mono")[famnum]font <- rep(rep(1:4, each = 3), 2)cex <- rep(1:2, each = 12)text3d(font, cex, famnum, texts = paste(family, font), adj = 0.5,        color = "blue", family = family, font = font, cex = cex)

Retrieve source code used to produce texture file.

Description

Internally,rgl works with PNG files for textures.If a texture is requested using a different format, a temporaryPNG file of the image will be saved. This function allowsyou to retrieve the original expression used to producethe texture.

Usage

textureSource(texture)

Arguments

texture

The filename of a texture file. If missing, the directorywhere texture files are stored will be returned.

Details

rgl creates a new file in the temporary directorywhenever a non-PNG texture is used. It will delete themwhen it knows there are no references and at the end of the session, but conceivably there will be situations where you need to delete them earlier. CallingtextureSource() with no arguments will giveyou the directory holding the textures so that they canbe deleted sooner.

Value

Iftexture is specified and it is the name of a temporary PNG texture file produced byrgl, the expression used to specify the texture will be returned. If it is the name of some other file,texture willbe returned.

If no argument is given, the session-specific directoryholding the temporary texture files will be returned.

See Also

material3d

Examples

xyz <- cbind(c(0,1,1,0), c(0,0,1,1), c(0,0,0,0))st <- xyz[,1:2]open3d()id <- quads3d(xyz, texcoords = st,                texture = as.raster(matrix(colors()[1:120], ncol = 10)),                col="white")material3d(id = id, "texture")textureSource(material3d(id = id, "texture"))

Find the direction away from the closest point in a 3d projection

Description

Jim Lemon'sthigmophobe function in theplotrix packagecomputes good directions for labels in a 2D plot. This functiondoes the same for a particular projection in a 3D plot byprojecting down to 2D and calling his function.

Usage

thigmophobe3d(x, y = NULL, z = NULL,               P = par3d("projMatrix"),               M = par3d("modelMatrix"),              windowRect = par3d("windowRect"))

Arguments

x,y,z

point coordinates. Any reasonable way of definingthe coordinates is acceptable. See the functionxyz.coords for details.

P,M,windowRect

The projection and modelview matrices, and the size and position of the display in pixels.

Details

Sincethigmophobe3d projects using fixedP andM,it will not necessarily choose good directions if the user rotatesthe display or makes any other change to the projection.

Value

A vector of values from 1 to 4 to be used as thepos argumentintext3d.

Note

The examplebelow shows how to update the directions during an animation; I find that the moving labels are distracting, and prefer to live with fixed ones.

Author(s)

Duncan Murdoch

References

plotrix

See Also

text3d

Examples

if (requireNamespace("plotrix", quietly = TRUE)) {  # Simulate some data  xyz <- matrix(rnorm(30), ncol = 3)    # Plot the data first, to establish the projection  plot3d(xyz)    # Now thigmophobe3d can choose directions  textid <- text3d(xyz, texts = 1:10, pos = thigmophobe3d(xyz))    # Update the label positions during an animation  if (interactive() && !rgl.useNULL()) {    spin <- spin3d(rpm = 5)    f <- function(time) {      par3d(skipRedraw = TRUE)      on.exit(par3d(skipRedraw = FALSE))      pop3d(id = textid)      # Need to rotate before thigmophobe3d is called      result <- spin(time)      par3d(userMatrix = result$userMatrix)      textid <<- text3d(xyz, texts = 1:10, pos = thigmophobe3d(xyz))      result    }    play3d(f, duration = 5)  } else    textid   # just print the static display}

Modal dialog for saving par3d settings

Description

This function opens a TCL/TK modal dialog to allow particular views of an RGL sceneto be saved.

Usage

tkpar3dsave(params = c("userMatrix", "scale", "zoom", "FOV"),          times = FALSE, dev = cur3d(), ...)

Arguments

params

Which parameters to save

times

Should times be saved as well?

dev

Which RGL device to work with

...

Additional parameters to pass totktoplevel

Details

This opens a TCL/TK modal dialog box withRecord andQuit buttons. Each timeRecord is clicked, a snapshot is taken of currentpar3d settings. WhenQuit is clicked, the dialog closes and the values are returned in a list.

Iftimes == TRUE, then the times at which the views are recorded will also be saved, so thattheplay3d function will play back with the same timing.

Value

A list of the requested components. Each one will consist of a list of values that werecurrent when theRecord button was clicked. These are suitable to be passed directlyto thepar3dinterp function.

Author(s)

Duncan Murdoch

See Also

par3d,par3dinterp

Examples

if (interactive() && !in_pkgdown_example()) {  # Record a series of positions, and then play them back immediately  # at evenly spaced times, in an oscillating loop  example(plot3d)  play3d( par3dinterp( tkpar3dsave() ) )  # As above, but preserve the click timings  # play3d( par3dinterp( tkpar3dsave(times=TRUE) ) )}

The former tkrgl package

Description

Functions from the formertkrgl package.

Details

Thetkrgl package contained functions to use TCL/TK to controlan RGL scene on screen. These functions have now been mergedinto thergl package, and thetkrgl package hasbeen archived.

To avoid conflicts with RGL names and to indicate the TCL/TK nature of these functions, they have all been prefixed withtk:

tkpar3dsave

Formerlytkrgl::par3dsave, allows interactivesaving of scene parameters.

tkspin3d,tkspinControl

Formerlytkrgl::spin3d andtkrgl::spinControl, create buttonsto spin the scene.

History:

0.2-2 First public release
0.3 Added possibility to control multiple windows
0.4 Compatibility with 2.0.0 tcltk package
0.5 Added continuous rotation
0.6 Added par3dsave
0.7 Added parameters totkspinControl, fixed startup
0.8 Minor fixes to pass checks
0.9 Merge functions intorgl

Create TCL/TK controller for RGL window

Description

This function creates a TCL/TK window containing buttons to spin and resize one or more RGL windows.

Usage

tkspin3d(dev = cur3d(), ...)

Arguments

dev

A vector of one or more RGL device numbers to control

...

Named parameters in that match named formal argumentstotkspinControl are passed there, while others are passed totktoplevel

Author(s)

Ming Chen and Duncan Murdoch

See Also

tkspinControl

Examples

if (interactive() && !in_pkgdown_example()) {    open3d()    points3d(rnorm(100), rnorm(100), rnorm(100), size=3)    axes3d()    box3d()    tkspin3d()}

Create a spin control in a TCL/TK window

Description

This function may be used to embed a spin control in a TCL/TK window.

Usage

tkspinControl(base, dev = cur3d(), continue=FALSE, speed=30, scale=100, ... )

Arguments

base

The TCL/TK frame in which to insert this control.

dev

A vector of one or more RGL device numbers to control.

continue

Initial setting for continuous rotation checkbox.

speed

Initial setting for speed slider.

scale

Initial setting for scale slider.

...

Additional parameters to pass totkframe

Author(s)

Ming Chen and Duncan Murdoch

See Also

spin3d

Examples

if (interactive() && !in_pkgdown_example()) {     library(tcltk)    open3d()    win1 <- cur3d()    plot3d(rexp(100), rexp(100), rexp(100), size=3, col='green')        open3d()    win2 <- cur3d()    plot3d(rt(100,2), rt(100,2), rt(100, 2), size=3, col='yellow')        open3d()    win3 <- cur3d()    plot3d(rexp(100), rexp(100), rexp(100), size=3, col='red')            open3d()    win4 <- cur3d()    plot3d(rbinom(100,10,0.5), rbinom(100,10,0.5), rbinom(100,10,0.5), size=3, col='cyan')        base <- tktoplevel()    tkwm.title(base, "Spinners")    con1 <- tkspinControl(base, dev=c(win1,win2))    con2 <- tkspinControl(base, dev=c(win3,win4))    tkpack(con1, con2)}

An HTML widget to toggle display of elements of a scene

Description

This function produces a button in an HTML scenethat will toggle the display of items in the scene.

Usage

toggleWidget(sceneId,              ids = tagged3d(tags), tags = NULL, hidden = integer(),             subscenes = NULL,              label,              ...)

Arguments

sceneId

The HTML id of the RGL scene being controlled,or an object as inplaywidget.

ids,hidden

The RGL id numbers of the objects to toggle. Those inidsare initially shown; those inhidden are initially hidden.

tags

Alternate way to specifyids. Ignored ifids isgiven.

subscenes

The subscenes in which to toggle the objects.

label

The label to put on the button. The default is setfrom the expression passed toids or the value oftags.

...

Additional arguments to pass toplaywidget.

Details

Likeplaywidget, this function is designedto work within thehtmlwidgets framework. If the value is printed, the button will be insertedinto the output.

It is also designed to work withmagrittr-stylepipes: the result ofrglwidget orother widgets can be piped into it to add it to a display. It can also appear first in the pipeline, ifsceneId is set toNA.

Value

A widget suitable for use in anRmarkdown-generated webpage, or elsewhere.

Author(s)

Duncan Murdoch

See Also

toggleButton for the older styleof HTML control. TheUser Interaction in WebGL vignettegives more details.

Examples

theplot <- plot3d(rnorm(100), rnorm(100), rnorm(100), col = "red")widget <- rglwidget(height = 300, width = 300) %>%  toggleWidget(theplot["data"],                hidden = theplot[c("xlab", "ylab", "zlab")],                label = "Points")if (interactive() || in_pkgdown_example())  widget

Triangulate a two-dimensional polygon

Description

This algorithm decomposes a general polygon into simplepolygons and uses the “ear-clipping” algorithm to triangulate it.Polygons with holes are supported.

Usage

triangulate(x, y = NULL, z = NULL, random = TRUE, plot = FALSE, partial = NA)

Arguments

x,y,z

Coordinates of a two-dimensional polygon in a format supported byxyz.coords. See Details for a description of proper input andhowz is handled.

random

Currently ignored, the triangulationis deterministic.

plot

Whether to plot the triangulation; mainly for debugging purposes.

partial

Currently ignored. Improper input will lead to undefined results.

Details

Normallytriangulate looks only at thex andycoordinates. However, if one of those is constant, it is replacedwith thez coordinate if present.

The algorithm works as follows. First, it breaks the polygon into pieces separated byNA values inx ory.Each of these pieces should be a simple, non-self-intersectingpolygon, not intersecting the other pieces. (Though some minor exceptions to this rule may work, noneare guaranteed). The nesting of these pieces isdetermined: polygons may contain holes, and theholes may contain other polygons.

Vertex order around the polygons does not affectthe results: whether a polygon is on the outside or inside of a region is determined by nesting.

Polygons should not repeat vertices. An attempt is made to detect if the final vertex matches the firstone. If so, it will be deleted with a warning.

The “outer” polygon(s) are then merged with thepolygons that they immediately contain, and each of thesepieces is triangulated using the ear-clipping algorithm from the references.

Finally, all the triangulated pieces are put together into oneresult.

Value

A three-by-n array giving the indices of the vertices of each triangle. (No vertices are added; only the originalvertices are used in the triangulation.)

The array has an integer vector attribute"nextvert"with one entry per vertex, giving the index of the next vertex to proceed counter-clockwise around outerpolygon boundaries, clockwise around inner boundaries.

Note

Not all inputs will succeed, though inputs satisfyingthe rules listed in the Details section should.

Author(s)

R wrapper code written by Duncan Murdoch; theearcut library has numerous authors.

References

This function uses the C++ version of theearcut library fromhttps://github.com/mapbox/earcut.hpp.

See Also

extrude3d for a solid extrusion of a polygon,polygon3d fora flat display; both usetriangulate.

Examples

theta <- seq(0, 2*pi, length.out = 25)[-25]theta <- c(theta, NA, theta, NA, theta, NA, theta, NA, theta)r <- c(rep(1.5, 24), NA, rep(0.5, 24), NA, rep(0.5, 24), NA, rep(0.3, 24), NA, rep(0.1, 24))dx <- c(rep(0, 24), NA, rep(0.6, 24), NA, rep(-0.6, 24), NA, rep(-0.6, 24), NA, rep(-0.6, 24))x <- r*cos(theta) + dxy <- r*sin(theta)plot(x, y, type = "n")polygon(x, y)triangulate(x, y, plot = TRUE)open3d()polygon3d(x, y, x - y, col = "red")

Create a solid of rotation from a two-dimensional curve

Description

This function “turns” the curve (as on a lathe) to form a solid of rotation along the x axis.

Usage

turn3d(x, y = NULL, n = 12, smooth = FALSE, ...)

Arguments

x,y

Points on the curve, in a form suitable forxy.coords.They values must be non-negative.

n

How many steps in the rotation?

smooth

logical; whether to add normals for a smooth appearance.

...

Additional parameters to pass totmesh3d.

Value

A mesh object containing triangles and/or quadrilaterals.

Author(s)

Fang He and Duncan Murdoch

See Also

extrude3d

Examples

x <- 1:10y <- rnorm(10)^2open3d()shade3d(turn3d(x, y), col = "green")

Set attributes of vertices

Description

This is a function to produce actions in a web display. Aplaywidget or Shinyinput control (e.g. asliderInput control)sets a value which controls attributes of a selection of vertices.

Usage

vertexControl(value = 0, values = NULL, vertices = 1, attributes,              objid = tagged3d(tag), tag,              param = seq_len(NROW(values)) - 1, interp = TRUE)

Arguments

value

The value to use for input (typicallyinput$valuein a Shiny app.) Not needed withplaywidget.

values

A matrix of values, each row corresponding to an input value.

vertices

Which vertices are being controlled? Specifyvertices as a number from 1 tothe number of vertices in theobjid.

attributes

A vector of attributes of a vertex,fromc("x", "y", "z", "red", "green", "blue", "alpha", "nx", "ny", "nz", "radii", "ox", "oy", "oz", "ts", "tt", "offset"). SeeDetails.

objid

A single RGL object id.

tag

An alternate way to specifyobjid.

param

Parameter values corresponding to each row ofvalues.

interp

Whether to interpolate between rows ofvalues.

Details

This functionmodifies attributes of vertices in a singleobject. Theattributes are properties of each vertexin a scene; not all are applicable to all objects. In order,they are: coordinates of the vertex"x", "y", "z", colorof the vertex"red", "green", "blue", "alpha", normal at the vertex"nx", "ny", "nz", radius of a sphere at the vertex"radius", origin within a texture"ox", "oy" andperhaps"oz", texture coordinates"ts", "tt".

Planes are handled specially. The coefficientsa, b, cin theplanes3d orclipplanes3d specification are controlled using"nx", "ny", "nz", andd is handled as"offset". Thevertices argument is interpretedas the indices of the planes when these attributes are set.

If only one attribute of one vertex is specified,values maybe given as a vector and will be treated as a one-column matrix. Otherwisevalues must be given as a matrix withncol(values) == max(length(vertices),length(attributes)). Thevertices andattributes vectors will be recycled to the same length, and entries from columnj ofvalues will be applied to vertexvertices[j], attributeattributes[j].

Thevalue argument is translated into a row (or two rows ifinterp = TRUE) ofvaluesby finding its location inparam.

Value

A list of class"rglControl" of cleaned up parametervalues, to be used in an RGL widget.

Author(s)

Duncan Murdoch

See Also

TheUser Interaction in WebGL vignettegives more details.

Examples

  saveopts <- options(rgl.useNULL = TRUE)  theta <- seq(0, 6*pi, length.out = 100)  xyz <- cbind(sin(theta), cos(theta), theta)  plot3d(xyz, type="l")  id <- spheres3d(xyz[1,,drop=FALSE], col="red")  widget <- rglwidget(width=500, height=300) %>%  playwidget(vertexControl(values=xyz,                           attributes=c("x", "y", "z"),                           objid = id, param=1:100),             start = 1, stop = 100, rate=10)  if (interactive() || in_pkgdown_example())    widget  options(saveopts)

Set up viewpoint

Description

Set the viewpoint orientation.

Usage

view3d( theta = 0, phi = 15, fov = 60, zoom = 1,         scale = par3d("scale"), interactive = TRUE, userMatrix,         type = c("userviewpoint", "modelviewpoint") )

Arguments

theta,phi

polar coordinates in degrees.theta rotates round the vertical axis.phi rotates round the horizontal axis.

fov

field-of-view angle in degrees

zoom

zoom factor

scale

real length 3 vector specifying the rescaling to apply to each axis

interactive

logical, specifying if interactive navigation is allowed

userMatrix

4x4 matrix specifying user point of view

type

which viewpoint to set?

Details

The data model can be rotated using the polar coordinatesthetaandphi. Alternatively, it can be set in a completely general way using the 4x4 matrixuserMatrix. IfuserMatrix is specified,theta andphi are ignored.

The pointing device of your graphics user-interface can also be used to set the viewpoint interactively. With the pointing device the buttons are by default set as follows:

left

adjust viewpoint position

middle

adjust field of view angle

right or wheel

adjust zoom factor

The user's view can be set withfov andzoom.

If thefov angle is set to 0, a parallel or orthogonalprojection is used. Small non-zero values (e.g. 0.01 or less, but not0.0) are likely to lead to rendering errors due to OpenGL limitations.

Prior to version 0.94, all of these characteristics were stored in one viewpoint object. With that release the characteristics are splitinto those that affect the projection (the user viewpoint) and those thataffect the model (the model viewpoint). By default, this functionsets both, but thetype argument can be used to limit the effect.

See Also

par3d

Examples

## Not run: # animated round trip tour for 10 secondsopen3d()shade3d(oh3d(), color = "red")start <- proc.time()[3]while ((i <- 36*(proc.time()[3] - start)) < 360) {  view3d(i, i/4); }## End(Not run)

Write Asymptote code for an RGL scene

Description

Asymptote is a language for 3D graphics thatis highly integrated with LaTeX. This isan experimental function towrite an Asymptote program to approximate an RGL scene.

Usage

writeASY(scene = scene3d(),         title = "scene",          outtype = c("pdf", "eps", "asy", "latex", "pdflatex"),          prc = TRUE,          runAsy = "asy %filename%",          defaultFontsize = 12,         width = 7, height = 7,         ppi = 100,         ids = tagged3d(tags),         tags = NULL,          version = "2.65")

Arguments

scene

RGL scene object

outtype

What type of file to write? See Details.

prc

Whether to produce an interactive PRC scene.

title

The base of the filename to produce.

runAsy

Code to run the Asymptote program.

defaultFontsize

The default fontsize for text.

width,height

Width and height of the output image, in inches.

ppi

“Pixels per inch” to assume when convertingline widths and point sizes (which RGL measures in pixels).

ids

If notNULL, write out just theseRGL objects.

tags

Alternate way to specifyids. Ignored ifids isgiven.

version

Asymptote version 2.44 had a definition for its “light()” functionthat was incompatibly changed in versions 2.47 and 2.50. The current code has been tested with version 2.65.If you are using an older version, setversionto your version number and it may work better.

Details

Asymptote is both a language describing a 2D or 3D graphic, and a program to interpretthat language and produce output in a varietyof formats including EPS, PDF (interactiveor static), etc.

The interactive scene produced withprc = TRUErequiresouttype = "pdf", and (as of thiswriting) has a number of limitations:

Value

The filename of the output file is returnedinvisibly.

Note

This function is currently under development and limited in the qualityof output it produces. Arguments will likelychange.

There are a number of differences between the interactive display in Asymptote and the display in RGL. In particular, many objects that area fixed size in RGL will scale with the image in Asymptote. Defaultshave been chosen somewhat arbitrarily; tweaking will likely be needed.

Material properties of surfaces are not yet implemented.

On some systems, the programasy usedto process the output has bugs and may fail. Run the exampleat your own risk!

Author(s)

Duncan Murdoch

References

J. C. Bowman and A. Hammerlindl (2008). Asymptote: A vector graphics language, TUGBOAT: The Communications of the TeX Users Group, 29:2, 288-294.

See Also

scene3d saves a copy of a scene to an R variable;rglwidget,writePLY,writeOBJ andwriteSTLwrite the scene to a file in various other formats.

Examples

## Not run: # On some systems, the program  "asy"  used# to process the output has bugs, so this may fail.x <- rnorm(20)y <- rnorm(20)z <- rnorm(20)plot3d(x, y, z, type = "s", col = "red")olddir <- setwd(tempdir())writeASY(title = "interactive")  # Produces interactive.pdfwriteASY(title = "noninteractive", prc = FALSE) # Produces noninteractive.pdfsetwd(olddir)## End(Not run)

Read and write Wavefront OBJ format files

Description

writeOBJ writes OBJ files. This is a file format thatis commonly used in 3D graphics applications. It does not represent text,but does represent points, lines, polygons (and many other types thatRGL doesn't support).readOBJ reads only some partsof OBJ files.

Usage

writeOBJ(con,          pointRadius = 0.005, pointShape = icosahedron3d(),          lineRadius = pointRadius, lineSides = 20,          pointsAsPoints = FALSE, linesAsLines = FALSE,          withNormals = TRUE, withTextures = TRUE,          separateObjects = TRUE,         ids = tagged3d(tags),         tags = NULL)readOBJ(con, ...)

Arguments

con

A connection or filename.

pointRadius,lineRadius

The radius of points and lines relative to the overall scale of the figure,if they are converted to polyhedra.

pointShape

A mesh shape to use for points if they are converted. It is scaled by thepointRadius.

lineSides

Lines are rendered as cylinders with this many sides.

pointsAsPoints,linesAsLines

Whether to convert points and lines to “point” and “line” records in the OBJ output.

withNormals

Whether to output vertex normals for smooth shading.

separateObjects

Whether to mark each RGL object as a separate object in the file.

withTextures

Whether to output texture coordinates.

ids

The identifiers (fromids3d) of theobjects to write. IfNULL, try to write everything.

tags

Alternate way to specifyids. Ignored ifids isgiven.

...

Additional arguments (typically justmaterial) to pass totmesh3d.

Details

The currentwriteOBJ implementation only outputs triangles, quads, planes, spheres,points, line segments, line strips and surfaces. It does not output materialproperties such as colors, since the OBJ format does not support the per-vertexcolors that RGL uses.

ThereadOBJ implementation canread faces, normals, and textures coordinates, but ignoresmaterial properties (including the specification of the texturefile to use). To read a file that uses a single texture,specify it in thematerial argument, e.g.readOBJ("model.OBJ", material = list(color = "white", texture = "texture.png")). There is no support for files that usemultiple textures.

The defaults forpointsAsPoints andlinesAsLines have beenchosen becauseBlender does not importpoints or lines, only polygons. If you are exporting to other software youmay want to change them.

If present, texture coordinates are output by default, but thetextures themselves are not.

Individual RGL objects are output as separate objects in the file whenseparateObjects = TRUE, the default.

The output file should be readable by Blender and Meshlab; the latter can write ina number of other formats, including U3D, suitable for import into a PDF document.

Value

writeObj invisibly returns the name of the connection to which the data was written.

readObj returns a mesh object constructedfrom the input file.

Author(s)

Duncan Murdoch

References

The file format was found athttp://www.martinreddy.net/gfx/3d/OBJ.specon November 11, 2012.

Blender is an open source 3D object editor. Seewww.blender.org for details.

See Also

scene3d saves a copy of a scene to an R variable;rglwidget,writeASY,writePLY andwriteSTLwrite the scene to a file in various other formats.

Examples

filename <- tempfile(fileext = ".obj")open3d()shade3d( icosahedron3d() )writeOBJ(filename)# The motivation for writing readObj() was to read a shape# file of Comet 67P/Churyumov-Gerasimenko, from the ESA.# The file no longer appears to be online, but may still be# available on archive.org.  Here was the original URL:#   cometurl <- "http://sci.esa.int/science-e/www/object/doc.cfm?fobjectid=54726"# This code would read and display it:#   open3d()#   shade3d(readOBJ(url(cometurl), #                   material = list(col = "gray")))# Textures are used in a realistic hand image available from# https://free3d.com/3d-model/freerealsichand-85561.html# Thanks to Monte Shaffer for pointing this out.# Decompress the files into the current directory, convert# hand_mapNew.jpg to hand_mapNew.png, then use## Not run: open3d()shade3d(readOBJ("hand.OBJ", material = list(color = "white", shininess = 1, texture = "hand_mapNew.png")))## End(Not run)

Write Stanford PLY format files

Description

This function writes PLY files. This is a simple file format thatis commonly used in 3D printing. It does not represent text,only edges and polygons. ThewritePLY function does the necessary conversions.

Usage

writePLY(con, format = c("little_endian", "big_endian", "ascii"),          pointRadius = 0.005, pointShape = icosahedron3d(),          lineRadius = pointRadius, lineSides = 20,          pointsAsEdges = FALSE, linesAsEdges = pointsAsEdges,          withColors = TRUE, withNormals = !(pointsAsEdges || linesAsEdges),          ids = tagged3d(tags), tags = NULL)

Arguments

con

A connection or filename.

format

Which output format. Defaults to little-endian binary.

pointRadius,lineRadius

The radius of points and lines relative to the overall scale of the figure,if they are converted to polyhedra.

pointShape

A mesh shape to use for points if they are converted. It is scaled by thepointRadius.

lineSides

Lines are rendered as cylinders with this many sides.

pointsAsEdges,linesAsEdges

Whether to convert points and lines to “Edge” records in the PLY output.

withColors

Whether to output vertex color information.

withNormals

Whether to output vertex normals for smooth shading.

ids

The identifiers (fromids3d) of theobjects to write. IfNULL, try to write everything.

tags

Select objects with matching tags. Ignoredifids is specified.

Details

The current implementation only outputs triangles, quads, planes, spheres,points, line segments, line strips and surfaces.

The defaults forpointsAsEdges andlinesAsEdges have beenchosen becauseBlender does not importlines, only polygons. If you are exporting to other software youmay want to change them.

Since the PLY format only allows one object per file, all RGL objectsare combined into a single object when output.

The output file is readable by Blender and Meshlab; the latter can write ina number of other formats, including U3D, suitable for import into a PDF document.

Value

Invisibly returns the name of the connection to which the data was written.

Author(s)

Duncan Murdoch

References

The file format was found onwww.mathworks.com on November 10, 2012at a URL that no longer exists; currently theformat is described atwww.mathworks.com/help/vision/ug/the-ply-format.html.

Blender is an open source 3D object editor. Seewww.blender.org for details.

See Also

scene3d saves a copy of a scene to an R variable;rglwidget,writeASY,writeOBJ andwriteSTLwrite the scene to a file in various other formats.

Examples

filename <- tempfile(fileext = ".ply")open3d()shade3d( icosahedron3d(col = "magenta") )writePLY(filename)

[8]ページ先頭

©2009-2025 Movatter.jp