def update_bounds(self):
     """ Updates the spheres bounds """
     mat = self._transform.get_mat()
     mid_point = mat.xform_point(Vec3(0, 0, 0))
     max_point = mat.xform_point(Vec3(1, 1, 1))
     radius = (mid_point - max_point).length()
     self._bounds = BoundingSphere(mid_point, radius)
     self._modified = True
 def __init__(self):
     """ Inits a new environment probe """
     RPObject.__init__(self)
     self.index = -1
     self.last_update = -1
     self._transform = TransformState.make_identity()
     self._bounds = BoundingSphere(Vec3(0), 1.0)
     self._modified = True
     self._parallax_correction = True
     self._border_smoothness = 0.1
Ejemplo n.º 3
0
def test_plane_contains_sphere():
    plane = BoundingPlane((0, 0, 1, 0))

    # Sphere above plane
    assert plane.contains(BoundingSphere((0, 0, 2), 1)) == BoundingVolume.IF_no_intersection

    # Sphere intersecting surface of plane
    assert plane.contains(BoundingSphere((0, 0, 0), 1)) == BoundingVolume.IF_possible | BoundingVolume.IF_some

    # Sphere below plane
    assert plane.contains(BoundingSphere((0, 0, -2), 1)) == BoundingVolume.IF_possible | BoundingVolume.IF_some | BoundingVolume.IF_all
Ejemplo n.º 4
0
    def load(self):
        Entity.load(self)

        self.setPos(self.cEntity.getOrigin())
        self.setHpr(self.cEntity.getAngles())

        self.setDepthWrite(False, 1)
        col = self.getEntityValueColor("_light")
        self.rgbColor = col
        self.setAttrib(
            ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne,
                                  ColorBlendAttrib.OOne), 1)

        self.hide(CIGlobals.ShadowCameraBitmask)

        self.spotlightLength = self.getEntityValueFloat(
            "SpotlightLength") / 16.0
        self.spotlightWidth = self.getEntityValueFloat("SpotlightWidth") / 16.0

        beamAndHalo = loader.loadModel(
            "phase_14/models/misc/light_beam_and_halo.bam")

        # Blend between halo and beam
        spotlightroot = self.attachNewNode('spotlightRoot')
        spotlightroot.setP(90)
        self.spotlight = beamAndHalo.find("**/beam")
        self.spotlight.setBillboardAxis()
        self.spotlight.reparentTo(spotlightroot)

        self.halo = CIGlobals.makeLightGlow(self.spotlightWidth)
        self.halo.reparentTo(self)

        beamAndHalo.removeNode()

        entPos = self.getPos()

        spotDir = self.getQuat().getForward()
        # User specified a max length, but clip that length so the spot effect doesn't appear to go through a floor or wall
        traceEnd = entPos + (spotDir * self.spotlightLength)
        endPos = self.bspLoader.clipLine(entPos, traceEnd)
        realLength = (endPos - entPos).length()
        self.spotlight.setSz(realLength)
        self.spotlight.setSx(self.spotlightWidth)

        self.spotlightDir = spotDir
        self.negSpotlightDir = -self.spotlightDir

        # Full beam, no halo
        self.setBeamHaloFactor(1.0)

        self.reparentTo(render)

        # Only update the spotlight if the object passes the Cull test.
        self.node().setFinal(True)
        clbk = CallbackNode('point_spotlight_callback')
        clbk.setCullCallback(CallbackObject.make(self.__spotlightThink))
        clbk.setBounds(BoundingSphere((0, 0, 0), 0))
        self.callback = self.attachNewNode(clbk)
        self.callback.hide(CIGlobals.ReflectionCameraBitmask)
        self.callback.hide(CIGlobals.ShadowCameraBitmask)
Ejemplo n.º 5
0
def makeSprite(name, texture, scale, add = False):
    from panda3d.core import (GeomVertexFormat, GeomVertexData, GeomEnums,
                              InternalName, GeomVertexWriter, GeomPoints,
                              Geom, GeomNode, NodePath, TextureStage,
                              TexGenAttrib, BoundingSphere)
    format = GeomVertexFormat.getV3()
    data = GeomVertexData(name + "_data", format, GeomEnums.UHStatic)
    writer = GeomVertexWriter(data, InternalName.getVertex())
    writer.addData3f((0, 0, 0))
    primitive = GeomPoints(GeomEnums.UHStatic)
    primitive.addVertex(0)
    primitive.closePrimitive()
    geom = Geom(data)
    geom.addPrimitive(primitive)
    geomNode = GeomNode(name)
    geomNode.addGeom(geom)
    np = NodePath(geomNode)
    np.setLightOff(1)
    np.setMaterialOff(1)
    np.setRenderModePerspective(True)
    ts = TextureStage('sprite')
    if add:
        ts.setMode(TextureStage.MAdd)
    np.setTexture(ts, texture)
    np.setTexGen(ts, TexGenAttrib.MPointSprite)

    np.setDepthWrite(False)
    np.setDepthOffset(1)
    np.setTransparency(True)
    np.node().setBounds(BoundingSphere((0, 0, 0), 1))
    np.node().setFinal(True)
    np.flattenStrong()
    np.setScale(scale)

    return np
 def __init__(self):
     self._slot = -1
     self._needs_update = True
     self._resolution = 512
     self._mvp = 0.0
     self._region = LVecBase2i(-1)
     self._region_uv = LVecBase2f(0.0)
     self._bounds = BoundingSphere()
Ejemplo n.º 7
0
 def update_bounds(self):
     """ Updates the spheres bounds """
     mat = self._transform.get_mat()
     mid_point = mat.xform_point(Vec3(0, 0, 0))
     max_point = mat.xform_point(Vec3(1, 1, 1))
     radius = (mid_point - max_point).length()
     self._bounds = BoundingSphere(mid_point, radius)
     self._modified = True
Ejemplo n.º 8
0
 def __init__(self):
     """ Creates a new point light. Remember to set a position
     and a radius """
     Light.__init__(self)
     DebugObject.__init__(self, "PointLight")
     self.bounds = BoundingSphere()
     self.spacing = 0.5
     self.bufferRadius = 0.0
     self.typeName = "PointLight"
Ejemplo n.º 9
0
    def is_sphere_in_frustum(self, point, radius):
        """Determine if a sphere resides in the camera frustum

        :param point: :py:class:`mathutils.Vector`
        :param radius: radius of sphere
        :rtype: bool
        """
        relative_point = self._nodepath.get_relative_point(base.render, point)
        bounds = BoundingSphere(relative_point, radius)
        return self._node.get_bounds().contains(bounds) in {BoundingSphere.IF_some, BoundingSphere.IF_all}
Ejemplo n.º 10
0
 def __init__(self):
     """ Inits a new environment probe """
     RPObject.__init__(self)
     self.index = -1
     self.last_update = -1
     self._transform = TransformState.make_identity()
     self._bounds = BoundingSphere(Vec3(0), 1.0)
     self._modified = True
     self._parallax_correction = True
     self._border_smoothness = 0.1
    def set_perspective_lens(self, fov, near_plane, far_plane, pos, direction):
        transform_mat = Mat4.translate_mat(-pos)
        temp_lens = PerspectiveLens(fov, fov)
        temp_lens.set_film_offset(0, 0)
        temp_lens.set_near_far(near_plane, far_plane)
        temp_lens.set_view_vector(direction, LVector3.up())
        self.set_matrix_lens(transform_mat * temp_lens.get_projection_mat())

        hexahedron = temp_lens.make_bounds()
        center = (hexahedron.get_min() + hexahedron.get_max()) * 0.5
        self._bounds = BoundingSphere(pos + center,
                                      (hexahedron.get_max() - center).length())
Ejemplo n.º 12
0
    def __init__(self, panda3d):
        # Inicialización de variables
        self.winsize = [0, 0]
        self.panda3d = panda3d
        self.panda3d.mouse_on_workspace = False

        # Desabilita el comportamiento por defecto de la camara
        self.panda3d.disable_mouse()

        # Llama a la función self.window_rezise_event cuando la ventana cambia de tamaño
        self.accept('window-event', self.window_rezise_event)
        # self.panda3d.accept('aspectRatioChanged', lambda: print("ss"))
        # Creamos el punto donde se centrará la cámara
        target_pos = Point3(0., 0., 0.)

        self.panda3d.cam_target = self.panda3d.render.attach_new_node("camera_target")
        self.panda3d.cam_target.set_pos(target_pos)
        self.panda3d.camera.reparent_to(self.panda3d.cam_target)
        self.panda3d.camera.set_y(-50.)
        
        # Definimos la cambinación de teclas para el control de la camara
        self.camera_active = False

        self.orbit_mouse_btn = "mouse2"
        self.orbit_keyboard_btn = "shift"
        self.orbit_mouse_reference = None
        self.orbit_camera_reference = None

        self.pan_mouse_btn = "mouse2"
        self.pan_keyboard_btn = "mouse2"
        self.pan_mouse_reference = None
        self.pan_camera_reference = None

        self.zoom_mouse_btn = "mouse2"
        self.zoom_keyboard_btn = "control"
        self.zoom_mouse_reference = None
        self.zoom_camera_reference = None

        # Establecemos los valores máximos y minimos para el zoom
        
        self.max_zoom = 10
        self.min_zoom = 0.1
        
        # Creamos la tarea de control de la camara
        self.panda3d.task_mgr.add(self.camera_control_task, "camera_control")

        # El movimiento de la rueda del mouse controla el zoom
        self.panda3d.accept("wheel_up", self.zoom_in)
        self.panda3d.accept("wheel_down", self.zoom_out)

        # Una fución de prueba para comprobar la posición del mouse en el modelo 3d
        # self.panda3d.accept("mouse1", self.entity_select)

        # Se establece la lente ortografica en lugar de la perspectiva
        self.lens_type = "OrthographicLens"
        self.set_lens(self.lens_type)

        # Agrega un indicador de ejes en la esquina inferior izquierda
        self.corner = self.panda3d.camera.attachNewNode("corner of screen")
        # self.axis = self.panda3d.loader.loadModel("data/geom/custom-axis")
        # self.axis = self.panda3d.loader.loadModel("data/geom/view_gizmo_F")
        self.view_gizmo = list()
        self.view_gizmo.append(self.panda3d.loader.loadModel("data/geom/view_gizmo_compass"))

        # self.view_gizmo.append(self.panda3d.loader.loadModel("data/geom/view_gizmo_L"))
        # self.view_cube = ViewGizmoZone()
        # self.view_cube.set_geom(self.axis)

        for gizmo_geom in self.view_gizmo:
            gizmo_geom.setLightOff(1)
            # gizmo_geom.setColorScale(1,1,1,1)
            gizmo_geom.setShaderInput("colorborders", LVecBase4(0, 0, 0, 0.25))

            gizmo = ViewGizmoZone()
            gizmo.set_geom(gizmo_geom)
            gizmo_geom.node().setBounds(BoundingSphere(Point3(0, 0, 0), 10))
            gizmo_geom.node().setFinal(True)

            #gizmo_geom.showTightBounds()
            # gizmo_geom.showBounds()



        self.show_view_gizmo()

        # Agregamos una luz puntual en la ubicación de la camara
        plight = DirectionalLight("camera_light")
        plight.setColor((1, 1, 1, 1))
        #plight.setAttenuation((1, 0, 0))
        #print("getMaxDistance {}".format(plight.getMaxDistance()))
        self.panda3d.plight_node = self.panda3d.render.attach_new_node(plight)
        self.panda3d.plight_node.setPos(0, -50, 0)
        self.panda3d.render.setLight(self.panda3d.plight_node)
        self.panda3d.plight_node.reparentTo(self.panda3d.camera)



        # Agregamos luz ambiental que disminuya las zonas oscuras
        alight = AmbientLight('alight')
        alight.setColor((0.3, 0.3, 0.3, 1))

        alnp = self.panda3d.render.attachNewNode(alight)
        self.panda3d.render.setLight(alnp)

        #def init_select_detection(self):
        self.traverser = CollisionTraverser("")
        # self.traverser.show_collisions(self.panda3d.render)
        self.picker_ray = CollisionRay()
        self.handler = CollisionHandlerQueue()

        self.picker_node = CollisionNode('mouseRay')
        self.picker_np = self.panda3d.camera.attachNewNode(self.picker_node)
        self.picker_node.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.picker_ray = CollisionRay()
        self.picker_node.addSolid(self.picker_ray)
        self.traverser.addCollider(self.picker_np, self.handler)
Ejemplo n.º 13
0
 def _computeLightBounds(self):
     """ Recomputes the bounds of this light. For a SpotLight, we for now
     use a simple BoundingSphere """
     self.bounds = BoundingSphere(Point3(self.position), self.radius * 2.0)
Ejemplo n.º 14
0
 def _computeLightBounds(self):
     """ Recomputes the bounds of this light. For a PointLight, this
     is simple, as it's only a BoundingSphere """
     self.bounds = BoundingSphere(Point3(self.position), self.radius)
Ejemplo n.º 15
0
class PointLight(Light, DebugObject):

    """ This light type simulates a PointLight. It has a position
    and a radius. The attenuation is computed based on a quadratic
    function.

    Shadows are simulated using a cubemap, which means that this light has
    6 Shadow maps, and when calling setShadowMapResolution() you are
    actually setting the resolution for all maps. 
    """

    def __init__(self):
        """ Creates a new point light. Remember to set a position
        and a radius """
        Light.__init__(self)
        DebugObject.__init__(self, "PointLight")
        self.bounds = BoundingSphere()
        self.spacing = 0.5
        self.bufferRadius = 0.0
        self.typeName = "PointLight"

    def getLightType(self):
        """ Internal method to fetch the type of this light, used by Light """
        return LightType.Point

    def _computeLightBounds(self):
        """ Recomputes the bounds of this light. For a PointLight, this
        is simple, as it's only a BoundingSphere """
        self.bounds.setCenter(self.position)
        self.bounds.setRadius(self.radius)

    def _updateDebugNode(self):
        """ Internal method to generate new debug geometry. """
        debugNode = NodePath("PointLightDebugNode")
        debugNode.setPos(self.position)

        # Create the inner image 
        cm = CardMaker("PointLightDebug")
        cm.setFrameFullscreenQuad()
        innerNode = NodePath(cm.generate())
        innerNode.setTexture(Globals.loader.loadTexture("Data/GUI/Visualization/PointLight.png"))
        innerNode.setBillboardPointEye()
        innerNode.reparentTo(debugNode)

        # Create the outer lines
        lineNode = debugNode.attachNewNode("lines")

        # Generate outer circles
        points1 = []
        points2 = []
        points3 = []
        for i in range(self.visualizationNumSteps + 1):
            angle = float(
                i) / float(self.visualizationNumSteps) * math.pi * 2.0
            points1.append(Vec3(0, math.sin(angle), math.cos(angle)))
            points2.append(Vec3(math.sin(angle), math.cos(angle), 0))
            points3.append(Vec3(math.sin(angle), 0, math.cos(angle)))

        self._createDebugLine(points1, False).reparentTo(lineNode)
        self._createDebugLine(points2, False).reparentTo(lineNode)
        self._createDebugLine(points3, False).reparentTo(lineNode)
        lineNode.setScale(self.radius)

        # Remove the old debug node
        self.debugNode.node().removeAllChildren()

        # Attach the new debug node
        debugNode.reparentTo(self.debugNode)
        # self.debugNode.flattenStrong()

    def _initShadowSources(self):
        """ Internal method to init the shadow sources """
        for i in range(6):
            source = ShadowSource()
            source.setupPerspectiveLens(1.0, self.radius, (100, 100))
            source.setResolution(self.shadowResolution)
            self._addShadowSource(source)

    def _updateShadowSources(self):
        """ Recomputes the position of the shadow sources. """

        # Position each 1 shadow source in 1 direction
        cubemapDirections = [
            Vec3(-1, 0, 0),
            Vec3(1, 0, 0),
            Vec3(0, -1, 0),
            Vec3(0, 1, 0),
            Vec3(0, 0, -1),
            Vec3(0, 0, 1),
        ]

        for index, direction in enumerate(cubemapDirections):
            self.shadowSources[index].setPos(self.position)
            self.shadowSources[index].lookAt(self.position + direction)

    def __repr__(self):
        """ Generates a string representation of this instance """
        return "PointLight[]"
Ejemplo n.º 16
0
class EnvironmentProbe(RPObject):
    """ Simple class, representing an environment probe """

    def __init__(self):
        """ Inits a new environment probe """
        RPObject.__init__(self)
        self.index = -1
        self.last_update = -1
        self._transform = TransformState.make_identity()
        self._bounds = BoundingSphere(Vec3(0), 1.0)
        self._modified = True
        self._parallax_correction = True
        self._border_smoothness = 0.1

    @property
    def modified(self):
        """ Returns whether the probe was modified since the last write """
        return self._modified

    @property
    def bounds(self):
        """ Returns the probes worldspace bounds """
        return self._bounds

    @property
    def parallax_correction(self):
        """ Returns whether parallax correction is enabled for this probe """
        return self._parallax_correction

    @parallax_correction.setter
    def parallax_correction(self, value):
        """ Sets whether parallax correction is enabled for this probe """
        self._parallax_correction = value
        self._modified = True

    @property
    def border_smoothness(self):
        """ Returns the border smoothness factor """
        return self._border_smoothness

    @border_smoothness.setter
    def border_smoothness(self, value):
        """ Sets the border smoothness factor """
        self._border_smoothness = value
        self._modified = True

    def set_pos(self, *args):
        """ Sets the probe position """
        self._transform = self._transform.set_pos(Vec3(*args))
        self.update_bounds()

    def set_hpr(self, *args):
        """ Sets the probe rotation """
        self._transform = self._transform.set_hpr(Vec3(*args))
        self.update_bounds()

    def set_scale(self, *args):
        """ Sets the probe scale """
        self._transform = self._transform.set_scale(Vec3(*args))
        self.update_bounds()

    def set_mat(self, matrix):
        """ Sets the probes matrix, overrides all other transforms """
        self._transform = TransformState.make_mat(matrix)
        self.update_bounds()

    def update_bounds(self):
        """ Updates the spheres bounds """
        mat = self._transform.get_mat()
        mid_point = mat.xform_point(Vec3(0, 0, 0))
        max_point = mat.xform_point(Vec3(1, 1, 1))
        radius = (mid_point - max_point).length()
        self._bounds = BoundingSphere(mid_point, radius)
        self._modified = True

    @property
    def matrix(self):
        """ Returns the matrix of the probe """
        return self._transform.get_mat()

    def write_to_buffer(self, buffer_ptr):
        """ Writes the probe to a given byte buffer """
        data, mat = [], Mat4(self._transform.get_mat())
        mat.invert_in_place()
        for i in range(4):
            for j in range(3):
                data.append(mat.get_cell(i, j))
        data += (float(self.index),
                 1.0 if self._parallax_correction else 0.0,
                 self._border_smoothness, 0)
        data.append(self._bounds.get_center().x)
        data.append(self._bounds.get_center().y)
        data.append(self._bounds.get_center().z)
        data.append(self._bounds.get_radius())
        byte_data = struct.pack("f" * 20, *data)

        # 4 = sizeof float, 20 = floats per cubemap
        bytes_per_probe = 4 * 20
        buffer_ptr.set_subdata(self.index * bytes_per_probe, bytes_per_probe, byte_data)

        self._modified = False
Ejemplo n.º 17
0
 def _computeLightBounds(self):
     self.bounds = BoundingSphere(Point3(self.position), self.radius)
class EnvironmentProbe(RPObject):
    """ Simple class, representing an environment probe """
    def __init__(self):
        """ Inits a new environment probe """
        RPObject.__init__(self)
        self.index = -1
        self.last_update = -1
        self._transform = TransformState.make_identity()
        self._bounds = BoundingSphere(Vec3(0), 1.0)
        self._modified = True
        self._parallax_correction = True
        self._border_smoothness = 0.1

    @property
    def modified(self):
        """ Returns whether the probe was modified since the last write """
        return self._modified

    @property
    def bounds(self):
        """ Returns the probes worldspace bounds """
        return self._bounds

    @property
    def parallax_correction(self):
        """ Returns whether parallax correction is enabled for this probe """
        return self._parallax_correction

    @parallax_correction.setter
    def parallax_correction(self, value):
        """ Sets whether parallax correction is enabled for this probe """
        self._parallax_correction = value
        self._modified = True

    @property
    def border_smoothness(self):
        """ Returns the border smoothness factor """
        return self._border_smoothness

    @border_smoothness.setter
    def border_smoothness(self, value):
        """ Sets the border smoothness factor """
        self._border_smoothness = value
        self._modified = True

    def set_pos(self, *args):
        """ Sets the probe position """
        self._transform = self._transform.set_pos(Vec3(*args))
        self.update_bounds()

    def set_hpr(self, *args):
        """ Sets the probe rotation """
        self._transform = self._transform.set_hpr(Vec3(*args))
        self.update_bounds()

    def set_scale(self, *args):
        """ Sets the probe scale """
        self._transform = self._transform.set_scale(Vec3(*args))
        self.update_bounds()

    def set_mat(self, matrix):
        """ Sets the probes matrix, overrides all other transforms """
        self._transform = TransformState.make_mat(matrix)
        self.update_bounds()

    def update_bounds(self):
        """ Updates the spheres bounds """
        mat = self._transform.get_mat()
        mid_point = mat.xform_point(Vec3(0, 0, 0))
        max_point = mat.xform_point(Vec3(1, 1, 1))
        radius = (mid_point - max_point).length()
        self._bounds = BoundingSphere(mid_point, radius)
        self._modified = True

    @property
    def matrix(self):
        """ Returns the matrix of the probe """
        return self._transform.get_mat()

    def write_to_buffer(self, buffer_ptr):
        """ Writes the probe to a given byte buffer """
        data, mat = [], Mat4(self._transform.get_mat())
        mat.invert_in_place()
        for i in range(4):
            for j in range(3):
                data.append(mat.get_cell(i, j))
        data += (float(self.index), 1.0 if self._parallax_correction else 0.0,
                 self._border_smoothness, 0)
        data.append(self._bounds.get_center().x)
        data.append(self._bounds.get_center().y)
        data.append(self._bounds.get_center().z)
        data.append(self._bounds.get_radius())
        byte_data = struct.pack("f" * 20, *data)

        # 4 = sizeof float, 20 = floats per cubemap
        bytes_per_probe = 4 * 20
        buffer_ptr.set_subdata(self.index * bytes_per_probe, bytes_per_probe,
                               byte_data)

        self._modified = False