def scene(t):
            """
            Returns the scene at time 't' (in seconds)
            """

            head_location = np.array(location) - np.array([0, 0, head_size])
            import vapory
            light = vapory.LightSource([15, 15, 1], 'color',
                                       [light_intensity] * 3)
            background = vapory.Box(
                [0, 0, 0], [1, 1, 1],
                vapory.Texture(
                    vapory.Pigment(
                        vapory.ImageMap('png',
                                        '"../files/VISUEL_104.png"', 'once')),
                    vapory.Finish('ambient', 1.2)), 'scale',
                [self.background_depth, self.background_depth, 0], 'translate',
                [
                    -self.background_depth / 2, -.45 * self.background_depth,
                    -self.background_depth / 2
                ])
            me = vapory.Sphere(
                head_location, head_size,
                vapory.Texture(vapory.Pigment('color', [1, 0, 1])))
            self.t = t
            self.update()
            objects = [background, me, light]

            for i_lame in range(self.N_lame):
                #print(i_lame, self.lame_length[i_lame], self.lame_width[i_lame])
                objects.append(
                    vapory.Box(
                        [
                            -self.lame_length[i_lame] / 2, 0,
                            -self.lame_width[i_lame] / 2
                        ],
                        [
                            self.lame_length[i_lame] / 2, self.lames_height,
                            self.lame_width[i_lame] / 2
                        ],
                        vapory.Pigment('color', [1, 1, 1]),
                        vapory.Finish('phong', 0.8, 'reflection', reflection),
                        'rotate',
                        (0, -self.lames[2, i_lame] * 180 / np.pi, 0),  #HACK?
                        'translate',
                        (self.lames[0, i_lame], 0, self.lames[1, i_lame])))

            objects.append(light)
            return vapory.Scene(vapory.Camera('angle', fov, "location",
                                              location, "look_at", look_at),
                                objects=objects,
                                included=["glass.inc"])
Example #2
0
def povray_test():
  """ Just a purple sphere """
  scene = vapory.Scene(  vapory.Camera('location',  [0.0, 0.5, -4.0],
                         'direction', [0,0,1.5],
                         'look_at',  [0, 0, 0]),
  
                  objects = [
  
                      vapory.Background("color", [0.85, 0.75, 0.75]),
  
                      vapory.LightSource([0, 0, 0],
                                    'color',[1, 1, 1],
                                    'translate', [-5, 5, -5]),
  
                      vapory.LightSource ([0, 0, 0],
                                      'color', [0.25, 0.25, 0.25],
                                      'translate', [600, -600, -600]),
  
  
                      vapory.Box([-0.5, -0.5, -0.5], [0.5, 0.5, 0.5],
                           vapory.Texture( vapory.Pigment( 'color', [1,0,0]),
                                    vapory.Finish('specular', 0.6),
                                    vapory.Normal('agate', 0.25, 'scale', 0.5)),
                          'rotate', [45,46,47])
                 ]
  )
  # We use antialiasing. Remove this option for faster rendering.
  scene.render("cube.png", width=300, height=300, antialiasing=0.001)
Example #3
0
    def __init__(self,world,sim):
        GLRealtimeProgram.__init__(self,"GLTest")
        self.world = world
        self.sim = sim
        self.anim = False
        
        #povray property
        self.povray_properties = {}
        
        #add 4 lights each with 5 meters from the robot
        povray.add_multiple_lights(self.povray_properties,self.world.robot(0),5.,4,spotlight=True,area=.1)
        
        #tell povray that all terrain will not be modified
        povray.mark_terrain_transient(self.povray_properties,self.world)
        
        #the robot will move, so we remove this line
        #povray.mark_robot_transient(self.povray_properties,self.world.robot(0))
        
        #overwrite material of floor to marble
        fin=vp.Finish('ambient',0.,'diffuse',.5,'specular',.15)
        nor=vp.Normal('granite',0.2,'warp {turbulence 1}','scale',.25)
        povray.set_material(self.povray_properties,self.world.terrain(0),fin,nor)

        #randomize robot link color
        import random
        for l in range(self.world.robot(0).numLinks()):
            lk=self.world.robot(0).link(l)
            lk.appearance().setColor(random.uniform(0.,1.),random.uniform(0.,1.),random.uniform(0.,1.))
Example #4
0
def povray_cells(goodArguments):
  with h5py.File(goodArguments.vbl_simulation_output_filename, 'r') as f:
    h5_cells_grp = f[goodArguments.grp_pattern + "/cells"]
    pos = h5_cells_grp['cell_center_pos']
    pos = np.asarray(pos)
    rad = h5_cells_grp['cell_radii']
    rad = np.asarray(rad)
    o2 = h5_cells_grp['o2']
    o2 = np.asarray(o2)
    x_min= np.min(pos[:,0])
    x_max = np.max(pos[:,0])
    center_x = x_min+0.5*(x_max-x_min)
    y_min= np.min(pos[:,1])
    y_max = np.max(pos[:,1])
    center_y = x_min+0.5*(y_max-y_min)
    z_min= np.min(pos[:,2])
    z_max = np.max(pos[:,2])
    center_z = z_min+0.5*(z_max-z_min)
    print('x: [%f,%f]' % (x_min, x_max))
    print('y: [%f,%f]' % (y_min, y_max))
    print('z: [%f,%f]' % (z_min, z_max))
    print('%f, %f, %f' %(center_x,center_y,center_z))
    #o2 = o2/np.max(o2)
#    x = pos[:,0]
#    y = pos[:,1]
#    z = pos[:,2]
#    s = rad[:,0]
  camera = vapory.Camera('location', [700,700,-700], 'look_at', [0,0,0])
  light = vapory.LightSource([1000,-1000,-1000], 'color', [1, 1, 1])
  light2 = vapory.LightSource([0,0,0], 'color',[1, 1, 1], 'translate', [1000,-1000,-1000] )
  light3 = vapory.LightSource([500,-1000,500], 'color', [1, 1, 1] )
  myObjectList = []
  myObjectList.append(light)
  myObjectList.append(light2)
  myObjectList.append(light3)
  
  cuttingY = vapory.Plane([0,1,0], 0,)
  cuttingX = vapory.Plane([1,0,0], -1,)
  max_rad = np.max(rad)
  max_o2 = np.max(o2)
  n= 10000
  for (aPosition, aRadius, aO2Value) in zip(pos[0:n], rad[0:n], o2[0:n]):
    thisSphere = vapory.Sphere( aPosition, aRadius[0])
    color = matplotlib.cm.hsv(aO2Value[0]/max_o2)
    #print(color[0:3])
    #cuttedSphere = vapory.Intersection(thisSphere, cuttingY, vapory.Texture( vapory.Pigment( 'color', color[0:3]  )))    
    #cuttedSphere = vapory.Intersection(thisSphere, cuttingY, cuttingX)    
    #cuttedSphere = thisSphere  
    #myObjectList.append(cuttedSphere)
    #myObjectList.append(thisSphere)
   # myObjectList.append(vapory.Sphere( aPosition, aRadius[0], vapory.Texture( vapory.Pigment( 'color', matplotlib.cm.Blues(aO2Value[0]/max_o2) ))))
    myObjectList.append(vapory.Sphere( aPosition, aRadius[0], vapory.Texture( vapory.Pigment( 'color', [1,0,0] ))))
    
  scene = vapory.Scene( camera, objects= myObjectList,  defaults = [vapory.Finish( 'ambient', 1.5)],)
  scene.render("purple_sphere.png", width=400, height=300,  antialiasing=0.01, remove_temp=True)
Example #5
0
def gen_img_settings_quality(l):
    """ generate the general povray settings"""

    lhalf = 0.5 * l

    ### sphere radius

    sphere_radius = 0.7

    ### RESOLUTION

    img_widthpx = 1024
    img_heightpx = 1024

    ### includes and defaults

    povray_includes = ["colors.inc", "textures.inc", "shapes.inc"]
    povray_defaults = [vapory.Finish( 'ambient', 0.1, \
           'diffuse', 0.65, \
          'specular', 0.5, \
          'shininess', 0.53, \
      'opacity', 1.0)]

    ### light sources

    sun1 = vapory.LightSource([lhalf, lhalf, -1.01 * lhalf], 'color', 'White')
    sun2 = vapory.LightSource([lhalf, lhalf, -1.01 * lhalf], 'color',
                              [0.7, 0.7, 0.7])

    ### background

    background = vapory.Background('color', [1, 1, 1])

    ### camera

    povray_cam = vapory.Camera('location', [lhalf, lhalf, -1.01*lhalf], \
                               'look_at', [lhalf,lhalf,0], 'angle', 90)

    ### text
    # If desired include this in the povray_objects - array declared in the loop
    #text1 = \
    #vapory.Text( 'ttf', '"timrom.ttf"' ,'"Division:"', 0.01, 0.0, \
    #'scale', [0.5,0.5,0.5],'rotate', \
    #[0,90,0], 'translate' , [0.0 , 15.0+2.75-1 , 15.0+1.5], \
    #vapory.Pigment('Black') )

    ### render quality

    quality = 10

    return sphere_radius, img_widthpx, img_heightpx, povray_includes, \
        povray_defaults, sun1, sun2, background, povray_cam, quality
Example #6
0
def PovrayArrow(position, direction, color):
    """
    This function creates the arrow with the library vapory
    (https://pypi.org/project/Vapory/). It helps to process the image.

    :param position: It is the position where the object is going to be ubicated.
    :type position: list
    :param direction: It is the course along which the object moves.
    :type direction: list
    :param color: It is representes by the RGB color model. It is an additive color
    model in which red, green, and blue light are added together in various ways to
    reproduce a broad array of colors.
    :type color: list

    :return: It returns an ``Union()`` of three 3D figures, that represent the
    ``PovrayArrow()``.
    :rtype: ``Union()``
    """
    position = numpy.array(position)
    direction = numpy.array(direction) * 0.9
    base_point_cylinder = position - 0.5 * direction
    cap_point_cone = position + 0.7 * direction
    cap_point_cylinder = base_point_cone = base_point_cylinder + 0.7 * direction

    radius_cylinder = 1 / 20
    base_radius_cone = 1 / 6

    texture = vapory.Texture(vapory.Pigment("color", color),
                             vapory.Finish("roughness", 0, "ambient", 0.2))

    cylinder = vapory.Cylinder(base_point_cylinder, cap_point_cylinder,
                               radius_cylinder, texture)

    cone = vapory.Cone(base_point_cone, base_radius_cone, cap_point_cone, 0.0,
                       texture)

    sphere = vapory.Sphere(
        position,
        2 * radius_cylinder,
        vapory.Texture(vapory.Pigment("color", [0, 0, 0])),
    )

    return vapory.Union(sphere, vapory.Union(cone, cylinder))
Example #7
0
def renderPopSpheres():
    nb_spheres = 50
    R = 5.
    centers = np.random.randint(100, size=(nb_spheres, 3))
    radius = np.random.randn(nb_spheres) * R + R
    couleurs = np.random.randint(255, size=(nb_spheres, 4)) / 255.

    camera = vapory.Camera('location', [150, 150, 150], 'look_at', [0, 0, 0])
    bg = vapory.Background('color', [1, 1, 1])
    light = vapory.LightSource([100, 100, 100], 'color', [1, 1, 1])
    light3 = vapory.LightSource([0, 0, 0], 'color', [1, 1, 1])
    light2 = vapory.LightSource([50, 50, 50], 'color', [1, 1, 1])

    obj = [light, light2, light3, bg]
    for i in range(nb_spheres):
        sphere = vapory.Sphere(
            centers[i, ], radius[i],
            vapory.Texture(
                vapory.Finish('ambient', 0, 'reflection', 0, 'specular', 0,
                              'diffuse', 1),
                vapory.Pigment('color', couleurs[i, ])))
        obj.append(sphere)
    scene = vapory.Scene(camera, objects=obj)
    scene.render("spheres.png", width=3000, height=3000)
Example #8
0
	def getScene(self, *, cameraLocation=[100,100,50], cameraTarget=[0,0,0], lightLocation=[100,100,100],
		                    lightColor=[1,1,1], backgroundColor=[0,0,0], objectColor=[0.5,0.5,0.5],
		                    rotationAxis=None, rotationAngle=None):
		# POVRay uses a left-handed coordinate system, so we have to flip the Z axis on all geometric vectors
		cameraLocation[2] = -cameraLocation[2]
		cameraTarget[2] = -cameraTarget[2]
		lightLocation[2] = -lightLocation[2]

		vertices = self.getUniqueVertices()
		if rotationAxis and rotationAngle:
			rotationMatrix = rotation_matrix(rotationAxis, rotationAngle)
			# Z axis must be flipped in vertex coords as well, before the transform
			vertexArgs = [ len(vertices) ] + [ list(np.dot(rotationMatrix, np.array([x,y,-z]))) for x,y,z in vertices ]
		else:
			vertexArgs = [ len(vertices) ] + [ [x,y,-z] for x,y,z in vertices ] # even if there is no rotation we must flip Z axis

		triangleIndices = self.getTriangleIndicesForUniqueVertices()
		faceArgs = [ len(triangleIndices) ] + list(map(list, triangleIndices))

		normales = np.zeros((len(vertices), 3))
		npvertices = np.array(vertices)
		for v0, v1, v2 in triangleIndices:
			triangleNormale = np.cross(npvertices[v1,:]-npvertices[v0,:], npvertices[v2,:]-npvertices[v0,:])
			triangleNormale /= np.linalg.norm(triangleNormale)
			triangleArea = np.dot(npvertices[v1,:]-npvertices[v0,:], npvertices[v2,:]-npvertices[v0,:])/2
			normales[v0,:] += triangleNormale*triangleArea
			normales[v1,:] += triangleNormale*triangleArea
			normales[v2,:] += triangleNormale*triangleArea
		normales /= np.linalg.norm(normales, axis=1, keepdims=True)

#		for i in range(len(vertices)):
#			print(f'Vertex {vertices[i]} has normale {normales[i]} (product {np.dot(vertices[i], normales[i])})')
#			print(f'{np.dot(vertices[i], normales[i])}')

		if rotationAxis and rotationAngle:
			rotationMatrix = rotation_matrix(rotationAxis, rotationAngle)
			# Z axis must be flipped in vertex coords as well, before the transform
			normaleArgs = [ len(vertices) ] + [ list(np.dot(rotationMatrix, np.array([x,y,-z]))) for x,y,z in [ normales[i,:] for i in range(len(vertices)) ] ]
		else:
			# even if there is no rotation we must flip Z axis
			normaleArgs = [ len(vertices) ] + [ [x,y,-z] for x,y,z in [ normales[i,:] for i in range(len(vertices)) ] ]

#		print('Rendering with camera at {} and light at {}'.format(str(cameraLocation), str(lightLocation)))

		asteroid = vpr.Mesh2(vpr.VertexVectors(*vertexArgs),
		                     vpr.NormalVectors(*normaleArgs),
		                     vpr.FaceIndices(*faceArgs),
		                     vpr.Texture(vpr.Pigment('color', 'rgb', [0.5, 0.5, 0.5]),
		                                 vpr.Normal('bumps', 0.75, 'scale', 0.0125),
		                                 vpr.Finish('phong', 0.1)
		                     )
		           )

#		                     vpr.Texture(vpr.Pigment('color', objectColor)))

		return vpr.Scene( vpr.Camera('location', cameraLocation, 'look_at', cameraTarget, 'sky', [0,0,-1]),
		                  objects = [ vpr.LightSource(lightLocation, 'color', lightColor),
		                              vpr.Background('color', backgroundColor),
		                              asteroid
		                  ],
		                  included = ["colors.inc", "textures.inc"]
#		                  ,defaults = [vpr.Finish( 'ambient', 0.0, 'diffuse', 0.0)]
		                  ,global_settings = [ 'ambient_light <0,0,0>' ]
		                )
Example #9
0
def plot_frames(beads, sim, ti, tf, savebase, colorid):
    """ plot frames within the specified time window"""

    ### define the color for the spheres

    print 'defining colors'
    if colorid == "id":
        sphere_rgbcolor = gen_colors_based_on_id(sim.nbeads, sim.npols,
                                                 beads.pid)
    elif colorid == "orient":
        sphere_rgbcolor = gen_colors_based_on_orient(sim.nbeads, sim.npols,
                                                     beads.ori)

    ### create povray settings

    print 'creating povray settings'
    sphere_radius, img_widthpx, img_heightpx, povray_includes, \
        povray_defaults, sun1, sun2, background, povray_cam, quality \
            = gen_img_settings_quality(sim.lx)

    zi = np.zeros((sim.nbeads), dtype=np.float32)

    ### set general plot properties

    os.system("mkdir -p " + savebase)
    savebase = data_separator.gen_folder_path(savebase, '_', sim.phaseparams)
    os.system("mkdir -p " + savebase)

    ### plot the frames

    for step in range(ti, tf):

        time = step * sim.dt
        print 'Step / Total : ', step, tf

        ### create povray items

        print 'generating povray item'
        particles = vapory.Object( \
            vapory.Union( \
                *[ vapory.Sphere([beads.xi[step, 0, j], beads.xi[step, 1, j],zi[j]], \
                    sphere_radius, vapory.Texture( \
                        vapory.Pigment('color', sphere_rgbcolor[j]), \
                            vapory.Finish('phong',1)) ) for j in range(0, sim.nbeads ) ] ) )

        ### generate povray objects

        print 'generating povray objects'
        povray_objects = [sun1, sun2, background, particles]
        ### create the scene
        scene = vapory.Scene(camera=povray_cam,
                             objects=povray_objects,
                             included=povray_includes,
                             defaults=povray_defaults)

        ### render image

        print 'rendering scene'
        savename = "pov-frame-" + "{0:05d}".format(int(step)) + ".png"
        scene.render(outfile=savename, width=img_widthpx, height=img_heightpx, \
            antialiasing=0.001, quality=quality, remove_temp=True)

        ### move the image to the correct destination

        os.system('mv ' + savename + ' ' + savebase)

    return
#set default parameter of radius
vis.properties["radius"] = 0.01
#set a different radius for world.terrain("PointCloud")
vis.properties["PointCloud"] = {"radius": 0.001}
#locate lights according to bounding box of the world, you can also set it by yourself
pos, tgt = povray.create_env_light_for_bb(vis.get_bb())
#add lights, turn it to pointlight by setting spotlight=False, area>0 means this is area light with soft shadow
povray.add_light(vis.properties,
                 pos,
                 tgt,
                 spotlight=True,
                 area=.1,
                 color=[2., 2., 2.])
#change the material of floor to stone
vis.properties["Floor"] = {"hide": False}
vis.properties["Floor"]["finish"] = vp.Finish('ambient', 0., 'diffuse', .5,
                                              'specular', .15)
vis.properties["Floor"]["normal"] = vp.Normal('granite', 0.2,
                                              'warp {turbulence 1}', 'scale',
                                              .25)
#change the material of VolumeGrid to metal
vis.properties["SDF"] = {}
preset = False
if preset:
    vis.properties["SDF"]["finish"] = vp.Finish('F_MetalB')
    #F_MetalB is a predefined material in povray, you have to include 'metal.inc' to use it
    vis.properties["included"] = ['metals.inc']
else:
    vis.properties["SDF"]["finish"] = vp.Finish('ambient', 0.30, 'brilliance',
                                                3, 'diffuse', 0.4, 'metallic',
                                                'specular', 0.70, 'roughness',
                                                1 / 60., 'reflection', .25)