Giter Site home page Giter Site logo

pythreejs's Introduction

pythreejs

Interactive demo on Binder Install from PyPI Install from conda-forge Reuse from npm Documentation Status Build Status

A Python / ThreeJS bridge for Jupyter Widgets.

Screencast

Installation

Using pip:

pip install pythreejs

or conda:

conda install -c conda-forge pythreejs

For a development install, see the contributing guide.

The extension should then be installed automatically for your Jupyter client.

For JupyterLab <3, you may also need to ensure nodejs is installed, and rebuild the application:

# conda install -c cond-forge 'nodejs>=12'
jupyter lab build

Troubleshooting

If the extension is not automatically installed, you can manually enable it

Jupyter Notebook Classic

jupyter nbextension list
jupyter nbextension install --py --symlink --sys-prefix pythreejs
jupyter nbextension enable --py --sys-prefix pythreejs
jupyter nbextension list

You should see:

Known nbextensions:
  ...
  jupyter-js-widgets/extension  enabled
    - Validating: OK

Note for developers: the --symlink argument on Linux or MacOS allows one to modify the JavaScript code in-place. This feature is not available on Windows.

JupyterLab

To perform a source installation:

## ensure you have nodejs install, e.g. with conda
# conda install -c conda-forge 'nodejs>=12'
jupyter labextension list
jupyter labextension install --no-build @jupyter-widgets/jupyterlab-manager
jupyter labextension install --no-build jupyter-datawidgets/extension
jupyter labextension install jupyter-threejs
jupyter labextension list

You should see:

JupyterLab v...
  ...
    jupyterlab-datawidgets v... enabled OK
    @jupyter-widgets/jupyterlab-manager v... enabled OK
    jupyter-threejs v... enabled OK

This approach is not recommended for JupyterLab 3, which enables federated modules, installed via pip, conda or other package managers, and does not require rebuilding the entire application.

Uninstallation

Using pip:

pip uninstall pythreejs

or conda:

conda uninstall pythreejs

If you applied any manual steps above, it may be necessary to remove the

Jupyter Notebook Classic

jupyter nbextension disable --py --sys-prefix pythreejs

Jupyter Lab

jupyter labextension uninstall jupyter-threejs

Open Source

This software is licensed under the BSD-3-Clause License.

pythreejs's People

Contributors

abelnation avatar agoose77 avatar akaszynski avatar aothms avatar avmarchenko avatar bollwyvl avatar davidmascharka avatar dependabot[bot] avatar farizrahmat avatar genevievebuckley avatar glyg avatar gouarin avatar jasongrout avatar jsb avatar logicalemotion avatar maartenbreddels avatar matthewturk avatar mgeier avatar nlooije avatar nrbgt avatar sylvaincorlay avatar toddrme2178 avatar vidartf avatar yungyuc avatar zeyuyun1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pythreejs's Issues

background reading, to better understand pythreejs code?

I have been studying pythreejs.py in order to understand ipywidgets, and tolearn how to create my own custom widget. And maybe as prelude to creating, as you did with sage, some higher level visualizations. Can I get a little advice from you? Perhaps you can point me towards background reading to fill in what I don't understand?

My confusion begins with the implicit operations which take place in the Mesh constructor, as called out of the first line of the Examples notebook:

ball = Mesh(geometry=SphereGeometry(radius=1),
            material=LambertMaterial(color='red'), 
            position=[2,1,0])

class Mesh(Object3d):
   _view_name = Unicode('MeshView').tag(sync=True)
   _model_name = Unicode('MeshModel').tag(sync=True)
   geometry = Instance(Geometry).tag(sync=True, **widget_serialization)
   material = Instance(Material).tag(sync=True, **widget_serialization)

In particular, I scratched my head over the absence of ctor arguments in the class definition. No init method. I imagine that traitlet configuration and the "*_widget_serialization" argument dig out the geometry and material parameters. Then the constructor of the base class, Object3d, is implicitly called and (?) the position is extracted from children (another traitlet initialized from *_widget_serialization perhaps?). That's my best guess...

Thus there is a lot going on here which I simply don't grasp. A few hours of web searching and reading have clarified a few things. If you can point me to some relevant documentation, some background material to read, I will be very grateful.

  • Paul

No shadows on PlainGeometry

For some reason shadows do not appear on the PlainGeometry objects I create, and I cannot figure out how to add it. I've included an example image of a tetrahedron on top of a BoxGeometry cube. You can see the cube is lit and also has shadows, but the tetrahedron is not.

Am I missing something? Is there a way to include shadows on a PlainGeometry object? Thanks!

screenshot from 2017-03-06 17 18 56

I am using pythreejs version 0.3.0 from conda-forge. Here's the code for copy/pasting:

vertices = [[0, 0, 0],
    [1, 0, 0],
    [0, 1, 0],
    [0, 0, 1]]

faces = [[0, 2, 1],
    [0, 3, 2],
    [0, 1, 3],
    [3, 1, 2]]

tet = p3js.PlainGeometry(vertices=vertices, faces=faces)
box = p3js.BoxGeometry(height=1, width=1, depth=1)

mat_red = p3js.LambertMaterial(color='red')

m_tet = p3js.Mesh(geometry=tet, material=mat_red, position=[-0.5, -0.5, 0.5])
m_box = p3js.Mesh(geometry=box, material=mat_red, position=[0, 0, 0])

dl = p3js.DirectionalLight(color='white', position=[0, 1, 5], intensity=1)
al = p3js.AmbientLight(color='#777777')

s =  p3js.Scene(children=[m_tet, m_box, al])

cam = p3js.PerspectiveCamera(position=[2, 3, 2], up=[0, 0, 1], children=[dl])

renderer = p3js.Renderer(camera=cam, scene=s, controls=[p3js.OrbitControls(controlling=cam)])
display(renderer)

HTML export

Hi,
Sorry for filling in an issue for this question. I was wondering if there is a way to export the outputs created by this library to a standalone html, or if it's better to directly work with three.js for that use.

offset hover_point with surf in Clickable Surface example

Setting the position for the hover_point only offsets it during initialization and translating the whole surf downwards, shifts the hover_point equally.

How would i go about offsetting the hover_point so that the whole sphere is above the surface?
and is there a way to snap the hover_point to the grid such that it only moves in discrete steps?

Fails under IPython 3.1, cannot import widget_serialization

From the comments near the imports at the top of pythree.js, it seems that pythreejs should work under IPython 3.x. However, it tries to import widget_serialization, which appears to only exist in the new Jupyter notebook.

Is this bug fixable, or do you intend to have the development version of the Jupyter notebook as a minimum dependency?

interactive widgets and pythreejs

Hi Guys! I have some (maybe simple) questions regarding the usage of pythreejs. I shall open a new issue for each. Here comes the first:
How can I use Interactive widgets and pythreejs combined ? If I simply try something like:

rnd=Rendnerer(... my setting...)

@interact(x=(-3,3,1))
def do_something(x):
      rnd.scene=make_my_scene(x)
      display(rnd)

I get a strange behavior. Every time I change the slider a new rendnering is displayed below my graph (webgl window). Altering the slider again I get yet another copy below the previous two.. Some properties of these graphs are linked.. like zooming and viewpoint. However they are showing different scenes (each reflecting their own slider position).
What is the proper way to update the widgets returned by the Renderer ? Using the above method produces no such doubling of output in case of simple matplotlib figures.. however I guess matplotlib figures are quite different than webgl stuff.. (am I right ?? )
Sorry for my obvious misconceptions but I am relatively new to ipython and a complete analphabet regarding javascript.
cheers
laszlo

Picker for Orthographic Camera

I believe that, if the camera is orthographic, then a pickingRay, rather that Raycaster needs to be used (see https://stackoverflow.com/questions/20361776/orthographic-camera-and-pickingray). Or there is a discussion here that may be of relevance mrdoob/three.js#599

Would love to try myself, but I have no experience in JS and I can't get the devlopment version to work :(

Here is my minimal use case, which does not work for orthographic (the picker only selects the closest object to the camera, irrespective of mouse position):

from pythreejs import *
import ipywidgets as widget
from IPython.display import display

perspective = False
container = Mesh(geometry=Geometry(), 
               material=BasicMaterial(),
               position=[0, 0, 0])

ball1 = Mesh(geometry=SphereGeometry(radius=1), 
                                    material=LambertMaterial(color='red'),
                                    position=[-.5, 0, 1])
ball2 = Mesh(geometry=SphereGeometry(radius=1), 
                                    material=LambertMaterial(color='blue'),
                                    position=[.5, 0, 0])
container.children=[ball1,ball2]

scene = Scene(children=[container, AmbientLight(color='#777777')])

if perspective:
    c = PerspectiveCamera(position=[0, 0, 10], up=[0, 0, 1],aspect=1.0)
else:
    c = OrthographicCamera(position=[0, 0, 10], up=[0, 0, 1],
                          left=-2,right=2,top=2,bottom=-2,near=.1,far=1000)
    
c.children=[DirectionalLight(color='white',
                position=[3, 5, 1],intensity=0.5)]
renderer = Renderer(camera=c, width='300',height='300',
                    scene=scene, 
                    controls=[OrbitControls(controlling=c)])

click_picker = Picker(root=scene.children[0], event='mousemove')
infobox = widget.HTML()
def change_info(change):
    infobox.value = 'Color: {}'.format(click_picker.object.material.color)
click_picker.observe(change_info, names=['object'])

renderer.controls = renderer.controls + [click_picker]

display(infobox)
display(renderer)

how to add object to render window

Is it possible to add an object to a renderer that has already been displayed?

initial rendering of scene

ball = Mesh(geometry=SphereGeometry(radius=1), material=LambertMaterial(color='red'), position=[2,1,0])
scene = Scene(children=[ball, AmbientLight(color=0x777777), make_text('Hello World!', height=.6)])
c = PerspectiveCamera(position=[0,5,5], up=[0,0,1], children=[DirectionalLight(color='white', 
                                                                             position=[3,5,1], 
                                                                             intensity=0.5)])
renderer = Renderer(camera=c, scene = scene, controls=[OrbitControls(controlling=c)])
ar = float(renderer.height)/(renderer.width)
renderer.width = 900
renderer.height = int(ar*800)
display(renderer)

later addition of new object into scene

ball2 = Mesh(geometry=IcosahedronGeometry(radius=1), material=LambertMaterial(color='green'), position=[3,1,0])
scene.children.append(ball2)

If I just call display(renderer) again, then the new object is in the scene, but it doesn't get updated in the initial renderer widget. @jdfreder, should I be calling something that comes from the widget interface instead to trigger a re-display of the first widget?

separate out renderer and figure

We've seen for a long time that since we create a new renderer each time we display a figure, we end up blowing past the browser webgl context limits. Instead, we should display a figure that takes a renderer, scene, and camera. That way it is easy to reuse a renderer for different displays. On the js side, the renderer should maybe be created as the model is created and attached to the model, as we really want a singleton renderer, not one for each view.

How to rotate objects?

I want to rotate a cylinder I've created because it doesn't like up with other geometry in my system. I think I am missing something--this should be fairly easy.

Minimal working example of what I want:

from pythreejs import *
import numpy as np
import math
from IPython.display import display
from ipywidgets import HTML, Text
from traitlets import link, dlink

my_geom = CylinderGeometry(radiusTop=5, radiusBottom=5, height=20)
my_geom.quaternion = [0, 0, 1,
                      90]  #my attempt at rotating the object, doesn't work

my_mesh = Mesh(
    geometry=my_geom,
    material=LambertMaterial(
        color='red', position=[0, 0, 0]))

scene = Scene(children=[my_mesh])

c = PerspectiveCamera(position=[0, 0, 20], up=[0, 0, 1], fov=90)

renderer = Renderer(
    camera=c, scene=scene, controls=[OrbitControls(controlling=c)])
display(renderer)

Thanks

latex annotation

Is there a simple way of using Latex annotations ? I toyed around with Sprites with TextTextures and sofar managed to get subscriptions (really awkwardly with two Sprites). But it would be really useful for teaching if I could use proper latex. Is there a proper way to do this ?

jupyter nbextension install --py --symlink --sys-prefix pythreejs

I am trying to install a development installation and am running into this error:
(To be honest I think it is because I'm using python3 but I didn't want to assume)

Traceback (most recent call last):
File "/Users/KaitlynChait/anaconda3/envs/py35/bin/jupyter-nbextension", line 11, in
sys.exit(main())
File "/Users/KaitlynChait/anaconda3/envs/py35/lib/python3.5/site-packages/jupyter_core/application.py", line 267, in launch_instance
return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
File "/Users/KaitlynChait/anaconda3/envs/py35/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance
app.start()
File "/Users/KaitlynChait/anaconda3/envs/py35/lib/python3.5/site-packages/notebook/nbextensions.py", line 969, in start
super(NBExtensionApp, self).start()
File "/Users/KaitlynChait/anaconda3/envs/py35/lib/python3.5/site-packages/jupyter_core/application.py", line 256, in start
self.subapp.start()
File "/Users/KaitlynChait/anaconda3/envs/py35/lib/python3.5/site-packages/notebook/nbextensions.py", line 745, in start
self.install_extensions()
File "/Users/KaitlynChait/anaconda3/envs/py35/lib/python3.5/site-packages/notebook/nbextensions.py", line 724, in install_extensions
**kwargs
File "/Users/KaitlynChait/anaconda3/envs/py35/lib/python3.5/site-packages/notebook/nbextensions.py", line 225, in install_nbextension_python
m, nbexts = _get_nbextension_metadata(module)
File "/Users/KaitlynChait/anaconda3/envs/py35/lib/python3.5/site-packages/notebook/nbextensions.py", line 1143, in _get_nbextension_metadata
'it is missing the _jupyter_nbextension_paths() method.'.format(module))
KeyError: 'The Python module pythreejs is not a valid nbextension, it is missing the _jupyter_nbextension_paths() method.'

VertexColors on Mesh Geometries

pythreejs doesn't seem to render vertexColors on Mesh geometries. A minimal example of what I was trying to do is:

geom = PlainGeometry(vertices=[[0,0,0],[1,0,0],[0,1,0],[0,0,1]],
                          faces=[[1,2,3],[0,1,2]],
                          colors = ['red',  'green', 'white', 'orange'])
mesh = Mesh(geometry=geom, material=BasicMaterial(vertexColors='VertexColors'))
scene = Scene(children=[mesh, DirectionalLight(color=0xccaabb, position=[0,10,0]),AmbientLight(color=0xcccccc)])
c = PerspectiveCamera(position=[0,2,2])
renderer = Renderer(camera=c, scene = scene, controls=[OrbitControls(controlling=c)])
display(renderer)

The expected result is two triangles with interpolated colors on faces from vertex values. Instead, two white triangles are rendered.
If Mesh is substituted by Line, the lines are interpolated.

Am I doing something wrong? Is this feature not implemented?
I'm trying to do scientific visualization of 3D mesh data on ipython using pythreejs and this feature would be really useful.

how to set lookAt vector

@jasongrout, I'm having trouble pointing the camera to the centroid of my scene, so I get clunky behavior from the orbital controls. Is there a direct way I can set it? I believe it's the lookAt vector in three.js, but I don't see it exposed by pythreejs.

missing dependencies on binder

I tried to run the examples via mybinder (through the mybinder badge). The following examples won't work due to missing modules:

  • Clickable Surface - skimage
  • Design your own texture - scipy

AutoGen: new screencast

Would be nice to add a new screencast that showcases the ability to just evaluate any object and have it rendered on screen to emphasize that you can render both the easy way and the hard way.

Renaming of THREE Geometry classes is confusing

Geometry -> PlainGeometry
PlaneGeometry -> SurfaceGeometry
??? -> FaceGeometry

Are these discrepancies necessary? Perhaps in the python side, Geometry base class could be renamed BaseGeometry?

master installation bug

Hi,

I'm trying to install master on an ubuntu 16.10 with python 2.7 install with conda

python setup.py develop or install

gives me the following error:

Installing build dependencies with npm.  This may take a while...

> [email protected] postinstall /home/jrking/git/pythreejs/js/node_modules/jupyter-js-widgets
> npm dedupe


> [email protected] prepublish /home/jrking/git/pythreejs/js
> webpack

/usr/bin/env: ‘node’: No such file or directory

npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: [email protected]
npm ERR! Linux 4.8.0-49-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install"
npm ERR! node v4.2.6
npm ERR! npm  v3.5.2
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! [email protected] prepublish: `webpack`
npm ERR! spawn ENOENT
npm ERR! 
npm ERR! Failed at the [email protected] prepublish script 'webpack'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the jupyter-threejs package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     webpack
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs jupyter-threejs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls jupyter-threejs
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/jrking/git/pythreejs/js/npm-debug.log
rebuilding js and css failed
missing files: ['/home/jrking/git/pythreejs/pythreejs/static/extension.js', '/home/jrking/git/pythreejs/pythreejs/static/index.js']
Traceback (most recent call last):
  File "setup.py", line 165, in <module>
    setup(**setup_args)
  File "/home/jrking/anaconda2/lib/python2.7/distutils/core.py", line 151, in setup
    dist.run_commands()
  File "/home/jrking/anaconda2/lib/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/home/jrking/anaconda2/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "/home/jrking/anaconda2/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg/setuptools/command/develop.py", line 34, in run
  File "/home/jrking/anaconda2/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg/setuptools/command/develop.py", line 115, in install_for_development
  File "/home/jrking/anaconda2/lib/python2.7/distutils/cmd.py", line 326, in run_command
    self.distribution.run_command(command)
  File "/home/jrking/anaconda2/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "setup.py", line 47, in run
    raise e
subprocess.CalledProcessError: Command '['npm', 'install']' returned non-zero exit status 1

an idea of what I should do?

Attribute to enable shadow maps

To have objects successfully send and receive shadows in Three, shadow maps needs to be enabled on the (WebGL) renderer. See e.g. this code from the Three documentation:

// Create a WebGLRenderer and turn on shadows in the renderer
var renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // default THREE.PCFShadowMap

I have not been able to find a way to set this from PyThreeJS. Is this currently possible? If not, could this be added? It might also help if the *LightShadow objects were exposed for manipulation.

Documentation on Picker class and attributes

I have been playing around with getting a simple gui going with PyThreeJS and I am really liking your work.

So far I got most things working, but while trying out some Pickers I ran into the problem that i don't know exactly how to use certain attributes of the Picker. For example, event takes a Unicode string and from the example I know it can take click, dblclick and mousemove, but i don't know any others. If i want a 'right-click' event, I wouldn't know where to look for the correct Unicode string.

Similarly i don't know how to use the root or picked attributes. For example, can root be any Mesh object? but i don't know how picked is used.

I tried looking at the ThreeJS documentation but as far as i can see Picker is a type of raycasting specific to the implementation of PyThreeJS or am i wrong? Is there some documentation i could refer to which explains the classes and their attributes (to some extent)?

bitmap output

Is there a way for producing a bitmap image of the rendnering ? Looking at some threejs examples I found that from threejs it is in principle possible to produce a png output, but if I am not mistaken pythreejs is not yet setup to do so.

`DirectionalLight` has no target

Three's DirectionalLight should have a target in addition to position. I also notice that the position and castShadow attributes of DirectionalLight are not correctly synced to the browser (at least, according to the console log).

For the following Python code:

light = pythreejs.DirectionalLight(
    intensity=0.6,
    position=[20., -20., 10.],
    castShadow=True,
    color='red',
)

The following is logged in the browser console:

THREE.DirectionalLight:

castShadow: false,
children: Array[0]
color: THREE.Color
eulerOrder: (...)
frustumCulled: true
id: 96
intensity: 0.6
layers: THREE.Layers
matrix: THREE.Matrix4
matrixAutoUpdate: true
matrixWorld: THREE.Matrix4
matrixWorldNeedsUpdate: false
modelViewMatrix: THREE.Matrix4
name: ""
needsUpdate: true
normalMatrix: THREE.Matrix3
parent: THREE.Scene
position: THREE.Vector3
quaternion: THREE.Quaternion
receiveShadow: undefined
renderOrder: 0
rotation: THREE.Euler
rotationAutoUpdate: true
scale: THREE.Vector3
shadow: THREE.LightShadow
target: THREE.Object3D
threejs_view: child
type: "DirectionalLight"
up: THREE.Vector3
useQuaternion: (...)
userData: Object
uuid: "57BA8404-C7C1-46C7-A1AC-6D456318C9C1"
visible: true
__proto__: THREE.Light

It does however work for Meshes.

Animation Example

Listed in the 'Examples to do' section is 'animate something through space'. Can you provide this example first, or suggestions on how to interact with the render loop so that animation can be done completely from the client side?

Displaying 3D graphics on nbviewer

The displayed output doesn't get rendered on Jupyter .ipynb notebooks on nbviewer

Has anyone achieved this with pythreejs?. The iPython notebook is supposed to be cached and showed as run last.

gitignore

Directory /pythreejs/pythreejs/ could be added to the .gitignore. It appears as untracked content.

Passing uniforms to shaders

I am trying to use some custom shaders, which rely on a uniform 'dimensions' attribute.

screen shot 2017-01-23 at 1 52 53 pm

I can't find any way to send a value for dimensions to the shader. In thee.js, it would work something like:

var material = new THREE.ShaderMaterial( {

	uniforms: {
		time: { value: 1.0 },
		resolution: { value: new THREE.Vector2() }
	},
	attributes: {
		vertexOpacity: { value: [] }
	},
	vertexShader: document.getElementById( 'vertexShader' ).textContent,
	fragmentShader: document.getElementById( 'fragmentShader' ).textContent

} );

However, there seems to be no equivalent to this in pythreejs. Has this not been implemented, or is there something I've missed?

PlainGeometry cannot be instantiated anymore.

I'm working from master, and when I try to create a PlainGeometry, I get an exception. PlainGeometrys work with the latest on PyPI.

geom = PlainGeometry(vertices=[[0, 0, 0]])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-25-b0b92456f9e4> in <module>()
      1 geom = three.PlainGeometry(
----> 2     vertices=[[0, 0, 1]]
      3 )

c:\users\cody\envs\pythreejs\lib\site-packages\ipywidgets\widgets\widget.py in __init__(self, **kwargs)
    201 
    202         Widget._call_widget_constructed(self)
--> 203         self.open()
    204 
    205     def __del__(self):

c:\users\cody\envs\pythreejs\lib\site-packages\ipywidgets\widgets\widget.py in open(self)
    220                 args['comm_id'] = self._model_id
    221 
--> 222             self.comm = Comm(**args)
    223             if buffers:
    224                 # FIXME: workaround ipykernel missing binary message support in open-on-init

c:\users\cody\envs\pythreejs\lib\site-packages\ipykernel\comm\comm.py in __init__(self, target_name, data, metadata, buffers, **kwargs)
     55             if self.primary:
     56                 # I am primary, open my peer.
---> 57                 self.open(data=data, metadata=metadata, buffers=buffers)
     58             else:
     59                 self._closed = False

c:\users\cody\envs\pythreejs\lib\site-packages\ipykernel\comm\comm.py in open(self, data, metadata, buffers)
     92                               data=data, metadata=metadata, buffers=buffers,
     93                               target_name=self.target_name,
---> 94                               target_module=self.target_module,
     95                               )
     96             self._closed = False

c:\users\cody\envs\pythreejs\lib\site-packages\ipykernel\comm\comm.py in _publish_msg(self, msg_type, data, metadata, buffers, **keys)
     63         data = {} if data is None else data
     64         metadata = {} if metadata is None else metadata
---> 65         content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
     66         self.kernel.session.send(self.kernel.iopub_socket, msg_type,
     67             content,

c:\users\cody\envs\pythreejs\lib\site-packages\ipykernel\jsonutil.py in json_clean(obj)
    165         out = {}
    166         for k,v in iteritems(obj):
--> 167             out[unicode_type(k)] = json_clean(v)
    168         return out
    169     if isinstance(obj, datetime):

c:\users\cody\envs\pythreejs\lib\site-packages\ipykernel\jsonutil.py in json_clean(obj)
    165         out = {}
    166         for k,v in iteritems(obj):
--> 167             out[unicode_type(k)] = json_clean(v)
    168         return out
    169     if isinstance(obj, datetime):

c:\users\cody\envs\pythreejs\lib\site-packages\ipykernel\jsonutil.py in json_clean(obj)
    165         out = {}
    166         for k,v in iteritems(obj):
--> 167             out[unicode_type(k)] = json_clean(v)
    168         return out
    169     if isinstance(obj, datetime):

c:\users\cody\envs\pythreejs\lib\site-packages\ipykernel\jsonutil.py in json_clean(obj)
    171 
    172     # we don't understand it, it's probably an unserializable object
--> 173     raise ValueError("Can't clean for JSON: %r" % obj)

ValueError: Can't clean for JSON: <memory at 0x06C6C730>

Camera.quaternion not updating scene

Hey, thanks for the great package

I am trying to sync the camera orientation of multiple scenes. However, changing the quaternion of the camera (which I assume is the best way) does not change the scene. Should this be the case?

Here is my minimal use case:

from pythreejs import *
import numpy as np
from IPython.display import display

scene = Scene(children=[Mesh(
    geometry=SphereGeometry(radius=0.1),
    material=LambertMaterial(color='red'),
    position=[i,j,0]) for i,j in np.mgrid[0:2,0:2].T.reshape((4,2))]+
              [AmbientLight(color='#777777')])
c = OrthographicCamera(position=[0,0,1],
        left=-2,right=2,top=2,bottom=-2,near=-2,
        children=[DirectionalLight(color='white', 
                    position=[3, 5, 1],intensity=0.5)])
control = TrackballControls(controlling=c)
renderer = Renderer(camera=c, height='400',width='400',
                    scene=scene,controls=[control])
display(renderer)

c.position = [0,1,0] # works
c.quaternion = [1,0,0,0] # doesn't work

support for Points?

After working through Examples.ipynb (very fine work, by the way) I am trying to create a bare bones 3d scatter plot. This javascript (adapted from here) when loaded in a simple html file works fine, but the THREE.Points class does not seem to be represented yet in pythreejs:

var pointGeometry = new THREE.Geometry();
for (var i=0; i<pointCount; i++) {
    var x = Math.random() * 100 - 50;
    var y = x*0.8+Math.random() * 20 - 10;
    var z = x*0.7+Math.random() * 30 - 15;
    pointGeometry.vertices.push(new THREE.Vector3(x,y,z));;
    pointGeometry.colors.push(new THREE.Color("red"));
    } // for i

var points = new THREE.Points(pointGeometry, mat);
scatterPlot.add(points);
scene.add(scatterPlot);
renderer.render(scene, camera);

Is support for the Points class coming? Or perhaps you suggest an alternative approach? Thanks for this excellent widget.

  • Paul

voxel_painter example runs with errors

In the example notebook voxel_painter.ipynb there are few errors when creating a material (or other object with color).

As far as I've find out, the bug is related to use of integer hex value for a color, while in ipywidgets library (I have ver. 6.0.0 installed with Anaconda) the string value, like 'blue' or '#feb74c' is expected.

When I've changed color specifications from ints to strings, the example was at least runnable (though with a warning and without interactivity in original three.js demo).

simple triangle

I am new to 3js. I have tried all the examples and they work fine. I want to render a simple triangle as shown in http://jsfiddle.net/yomotsu/gyPJQ/

and I have the following code:
geom = Geometry(vertices=[[0,0,0],[30,0,0],[30,30,0]],
faces=[[0,1,2]],
colors = ['red', 'blue', 'green'])
mesh = Mesh(geometry=geom, material=BasicMaterial(vertexColors='VertexColors'))
scene = Scene(children=[mesh,AmbientLight(color='#cccccc')])
c = PerspectiveCamera(position=[0, 0, 100], fov = 40, aspect = 6/4, near = 1, far = 1000)
renderer = Renderer(camera=c, scene = scene, controls=[OrbitControls(controlling=c)])
display(renderer)

It compiles fine but I do not see anything. Can someone please let me know what might be wrong here?

displays only after moving camera

Following code shows black screen, and renders correctly only after i move the camera around, or change some property value:

# create cart and pole
pole_box = Mesh(geometry=BoxGeometry(width=0.3, height=5, depth=0.3), material=LambertMaterial(color='blue'), position=[0,2.5,0])
pole = Mesh(geometry=BoxGeometry(width=0, height=0, depth=0), material=LambertMaterial(color='white'), position=[0,0,0], children=[pole_box])
cart = Mesh(geometry=BoxGeometry(width=4, height=1, depth=3), material=LambertMaterial(color='red'), position=[0,0,0], 
            children=[pole_box])
scene = Scene(children=[cart, AmbientLight(color=0x777777)])
c = PerspectiveCamera(position=[0,0,15], up=[0,1,0], children=[DirectionalLight(color='white', 
                                                                             position=[3,5,1], 
                                                                             intensity=0.5)])
renderer = Renderer(camera=c, scene = scene, controls=[OrbitControls(controlling=c)])
display(renderer)

I would like to help solve it, but my Javascript skills are not up to task.
Thanks for the great library!

From @ivmi, at https://github.com/jasongrout/pythreejs/issues/18#issuecomment-113442090

Enormous widget state

Steps to repoduce:

  • Open a new notebook with the following code (extracted from voxel_painter example notebook):
import pythreejs as three

sizex = sizey = 500

surf_geo = three.SurfaceGeometry(
    z = [0]*sizex*sizey,
    width = 2*sizex,
    height = 2*sizey,
    width_segments = 2*sizex//stepx,
    height_segments = 2*sizey//stepy,
)
  • Save notebook with widget state.

Result:
Notebook has more than 500*500 = 250'000 lines, as the z variable is getting one line per entry. This is sufficient to e.g. cause several diff tools to grind to a halt (git gui, github desktop, but not nbdime-web :D).

This might actually be a problem with how Notebook stores lists, but maybe there is a better way to save this?

Related IPyWidgets issue:
The widget state will be kept even after the outputs are cleared. Particularly for the "clear all outputs" action, you would expect all widget state to be cleared as well (I'm not certain how hard it would be to also handle clearing of individual outputs). Now, the only way to clear the widget state is to restart the kernel and click "save notebook with widgets".

Brower-side leaks

If I assign a lot to pytheejs object's properties, browser eventually start to leak memory (2-3Gb on chromium) and crash.

Naive update infinite loop

The new ipywidgets _view_count mechanism combined with the very naive update function in things like SurfaceView (https://github.com/jovyan/pythreejs/blob/bc60487d95e98f25c163eed65509da72f2dfd997/js/src/jupyter-threejs.js#L574) I think creates an infinite loop, where creating a view updates the model's view count, which then creates a new view, etc.

Clearly pythreejs needs to be smarter about updates, but I also wonder how common this might be, and how much having an automatic _view_count trip people up.

CC @maartenbreddels, @SylvainCorlay.

Appending objects to scene.children

per this TODO, to add objects to scene.children from a linked function it is not possible to simply do:

scene.children.append(object)

instead according to the example notebook, we use:

scene.children = list(scene.children) + [point]

First, why is this as i don't understand why? and, second, I would propose to allow the use of the first method as it is typical Python usage.

multiple Rendnerings side by side

Is it possible to put two Rendnerings side by side ? I guess this is a widget question and I need to immerse myself in to widgets a bit more. But are there any caveats ?
(I guess this is one of the rookie ones..)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.