def make_SB(pos, hpr):

            #use this to construct a torus geom.
            #import torus
            #geom = torus.make_geom()

            geom = (loader.load_model('models/torus.egg').find_all_matches(
                '**/+GeomNode').get_path(0).node().modify_geom(0))

            geomNode = GeomNode('')
            geomNode.add_geom(geom)

            node = BulletSoftBodyNode.make_tri_mesh(info, geom)
            node.link_geom(geomNode.modify_geom(0))

            node.generate_bending_constraints(2)
            node.get_cfg().set_positions_solver_iterations(2)
            node.get_cfg().set_collision_flag(
                BulletSoftBodyConfig.CF_vertex_face_soft_soft, True)
            node.randomize_constraints()
            node.set_total_mass(50, True)

            softNP = self.worldNP.attach_new_node(node)
            softNP.set_pos(pos)
            softNP.set_hpr(hpr)
            self.world.attach(node)

            geomNP = softNP.attach_new_node(geomNode)
Exemplo n.º 2
0
class Orbit(VisibleObject):
    ignore_light = True
    default_shown = False
    selected_color = LColor(1.0, 0.0, 0.0, 1.0)
    appearance = None
    shader = None

    def __init__(self, body):
        VisibleObject.__init__(self, body.get_ascii_name() + '-orbit')
        self.body = body
        self.owner = body
        self.nbOfPoints = 360
        self.orbit = self.find_orbit(self.body)
        self.color = None
        self.fade = 0.0
        if not self.orbit:
            print("No orbit for", self.get_name())
            self.visible = False

    def get_oid_color(self):
        if self.body is not None:
            return self.body.oid_color
        else:
            return LColor()

    @classmethod
    def create_shader(cls):
        cls.appearance = ModelAppearance(attribute_color=True)
        if settings.use_inv_scaling:
            vertex_control = LargeObjectVertexControl()
        else:
            vertex_control = None
        cls.shader = BasicShader(lighting_model=FlatLightingModel(), vertex_control=vertex_control)

    def check_settings(self):
        if self.body.body_class is None:
            print("No class for", self.body.get_name())
            return
        self.set_shown(settings.show_orbits and bodyClasses.get_show_orbit(self.body.body_class))

    def find_orbit(self, body):
        if body != None:
            if not isinstance(body.orbit, FixedOrbit):
                return body.orbit
            else:
                return None, None
        else:
            return None, None

    def set_selected(self, selected):
        if selected:
            self.color = self.selected_color
        else:
            self.color = self.parent.get_orbit_color()
        if self.instance:
            self.instance.setColor(srgb_to_linear(self.color * self.fade))

    def create_instance(self):
        self.vertexData = GeomVertexData('vertexData', GeomVertexFormat.getV3(), Geom.UHStatic)
        self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex')
        delta = self.body.parent.get_local_position()
        if self.orbit.is_periodic():
            epoch = self.context.time.time_full - self.orbit.period / 2
            step = self.orbit.period / (self.nbOfPoints - 1)
        else:
            #TODO: Properly calculate orbit start and end time
            epoch = self.orbit.get_time_of_perihelion() - self.orbit.period * 5.0
            step = self.orbit.period * 10.0 / (self.nbOfPoints - 1)
        for i in range(self.nbOfPoints):
            time = epoch + step * i
            pos = self.orbit.get_position_at(time) - delta
            self.vertexWriter.addData3f(*pos)
        self.lines = GeomLines(Geom.UHStatic)
        for i in range(self.nbOfPoints-1):
            self.lines.addVertex(i)
            self.lines.addVertex(i+1)
        if self.orbit.is_periodic() and self.orbit.is_closed():
            self.lines.addVertex(self.nbOfPoints-1)
            self.lines.addVertex(0)
        self.geom = Geom(self.vertexData)
        self.geom.addPrimitive(self.lines)
        self.node = GeomNode(self.body.get_ascii_name() + '-orbit')
        self.node.addGeom(self.geom)
        self.instance = NodePath(self.node)
        self.instance.setRenderModeThickness(settings.orbit_thickness)
        self.instance.setCollideMask(GeomNode.getDefaultCollideMask())
        self.instance.node().setPythonTag('owner', self)
        self.instance.reparentTo(self.context.annotation)
        if self.color is None:
            self.color = self.parent.get_orbit_color()
        self.instance.setColor(srgb_to_linear(self.color * self.fade))
        self.instance_ready = True
        if self.shader is None:
            self.create_shader()
        self.shader.apply(self, self.appearance)
        self.shader.update(self, self.appearance)

    def update_geom(self):
        geom = self.node.modify_geom(0)
        vdata = geom.modify_vertex_data()
        vwriter = GeomVertexRewriter(vdata, InternalName.get_vertex())
        #TODO: refactor with above code !!!
        delta = self.body.parent.get_local_position()
        if self.orbit.is_periodic():
            epoch = self.context.time.time_full - self.orbit.period
            step = self.orbit.period / (self.nbOfPoints - 1)
        else:
            #TODO: Properly calculate orbit start and end time
            epoch = self.orbit.get_time_of_perihelion() - self.orbit.period * 5.0
            step = self.orbit.period * 10.0 / (self.nbOfPoints - 1)
        for i in range(self.nbOfPoints):
            time = epoch + step * i
            pos = self.orbit.get_position_at(time) - delta
            vwriter.setData3f(*pos)

    def check_visibility(self, pixel_size):
        if self.parent.parent.visible and self.parent.shown and self.orbit:
            distance_to_obs = self.parent.distance_to_obs
            if distance_to_obs > 0.0:
                size = self.orbit.get_apparent_radius() / (distance_to_obs * pixel_size)
            else:
                size = 0.0
            self.visible = size > settings.orbit_fade
            self.fade = min(1.0, max(0.0, (size - settings.orbit_fade) / settings.orbit_fade))
            if self.color is not None and self.instance is not None:
                self.instance.setColor(srgb_to_linear(self.color * self.fade))
        else:
            self.visible = False

    def update_instance(self, camera_pos, camera_rot):
        if self.instance:
            self.place_instance_params(self.instance,
                                       self.body.parent.scene_position,
                                       self.body.parent.scene_scale_factor,
                                       LQuaternion())
            self.shader.update(self, self.appearance)

    def update_user_parameters(self):
        if self.instance is not None:
            self.update_geom()
Exemplo n.º 3
0
class Skidmark(GameObject):
    def __init__(self, whl_pos, whl_radius, car_h):
        GameObject.__init__(self)
        self.radius = whl_radius
        v_f = GeomVertexFormat.getV3()
        vdata = GeomVertexData('skid', v_f, Geom.UHDynamic)
        prim = GeomTriangles(Geom.UHStatic)
        self.vtx_cnt = 1
        self.last_pos = whl_pos
        geom = Geom(vdata)
        geom.add_primitive(prim)
        self.node = GeomNode('gnode')
        self.node.add_geom(geom)
        nodepath = self.eng.gfx.root.attach_node(self.node)
        nodepath.set_transparency(True)
        nodepath.set_depth_offset(1)
        nodepath.node.set_two_sided(True)  # for self-shadowing issues
        self.__set_material(nodepath)
        nodepath.p3dnode.set_bounds(OmniBoundingVolume())
        self.add_vertices(whl_radius, car_h)
        self.add_vertices(whl_radius, car_h)

        def alpha(time, n_p):
            if not n_p.is_empty:
                n_p.node.set_shader_input('alpha', time)
            # this if seems necessary since, if there are skidmarks and you
            # exit from the race (e.g. back to the menu), then alpha is being
            # called from the interval manager even if the interval manager
            # correctly says that there are 0 intervals.

        self.remove_seq = Sequence(
            Wait(8), LerpFunc(alpha, 8, .5, 0, 'easeInOut', [nodepath]),
            Func(nodepath.remove_node))
        self.remove_seq.start()

    @staticmethod
    def __set_material(nodepath):
        # mat = Material()
        # mat.set_ambient((.35, .35, .35, .5))
        # mat.set_diffuse((.35, .35, .35, .5))
        # mat.set_specular((.35, .35, .35, .5))
        # mat.set_shininess(12.5)
        # nodepath.set_material(mat)
        nodepath.node.set_shader(Shader.make(Shader.SL_GLSL, vert, frag))
        nodepath.node.set_shader_input('alpha', .5)

    def add_vertices(self, whl_radius, car_h):
        base_pos = self.last_pos + (0, 0, -whl_radius + .05)
        rot_mat = Mat4()
        rot_mat.set_rotate_mat(car_h, (0, 0, 1))
        vdata = self.node.modify_geom(0).modify_vertex_data()
        vwriter = GeomVertexWriter(vdata, 'vertex')
        vwriter.set_row(vdata.get_num_rows())
        vwriter.add_data3f(base_pos + rot_mat.xform_vec((-.12, 0, 0)))
        vwriter.add_data3f(base_pos + rot_mat.xform_vec((.12, 0, 0)))
        cnt = self.vtx_cnt
        prim = self.node.modify_geom(0).modify_primitive(0)
        if cnt >= 3:
            prim.add_vertices(cnt - 3, cnt - 2, cnt - 1)
            prim.add_vertices(cnt - 2, cnt, cnt - 1)
        self.vtx_cnt += 2

    def update(self, whl_pos, car_h):
        if (whl_pos - self.last_pos).length() > .2:
            self.last_pos = whl_pos
            self.add_vertices(self.radius, car_h)

    def destroy(self):
        self.remove_seq = self.remove_seq.finish()
        GameObject.destroy(self)
Exemplo n.º 4
0
class PointCloud():
    name: str
    node_path: NodePath
    geom_node: GeomNode

    def __init__(self, name='point_cloud', thickness: float = 3) -> None:
        self.name = name
        self.geom_node = GeomNode(self.name)
        self.node_path = NodePath(self.geom_node)
        self.node_path.set_render_mode_wireframe()
        self.node_path.set_render_mode_thickness(thickness)
        self.node_path.set_antialias(AntialiasAttrib.MPoint)

    @staticmethod
    def __make_points(vertices, colours=None, geom: Geom = None) -> Geom:
        """
        This function is largely inspired by panda3d_viewer's implementation.

        Copyright (c) 2020, Igor Kalevatykh

        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
        EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
        MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
        IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
        DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
        OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
        OR OTHER DEALINGS IN THE SOFTWARE.
        """

        if not isinstance(vertices, np.ndarray):
            vertices = np.asarray(vertices, dtype=np.float32)

        if colours is not None:
            if not isinstance(colours, np.ndarray):
                colours = np.asarray(colours)
            if colours.dtype != np.uint8:
                colours = np.uint8(colours * 255)
            vertices = np.column_stack((vertices.view(dtype=np.uint32).reshape(-1, 3),
                                        colours.view(dtype=np.uint32)))

        data = vertices.tostring()

        if geom is None:
            if vertices.strides[0] == 12:
                vformat = GeomVertexFormat.get_v3()
            elif vertices.strides[0] == 16:
                vformat = GeomVertexFormat.get_v3c4()
            else:
                raise ValueError('Incompatible point clout format: {},{}'.format(vertices.dtype, vertices.shape))

            vdata = GeomVertexData('vdata', vformat, Geom.UHDynamic)
            vdata.unclean_set_num_rows(len(vertices))
            vdata.modify_array_handle(0).set_subdata(0, len(data), data)

            prim = GeomPoints(Geom.UHDynamic)
            prim.clear_vertices()
            prim.add_consecutive_vertices(0, len(vertices))
            prim.close_primitive()

            geom = Geom(vdata)
            geom.add_primitive(prim)
        else:
            vdata = geom.modify_vertex_data()
            vdata.unclean_set_num_rows(len(vertices))
            vdata.modify_array_handle(0).set_subdata(0, len(data), data)

            prim = geom.modify_primitive(0)
            prim.clear_vertices()
            prim.add_consecutive_vertices(0, len(vertices))
            prim.close_primitive()

        return geom

    def update(self, vertices, colours=None) -> None:
        if self.geom_node.get_num_geoms() == 0:
            self.geom = self.__make_points(vertices, colours)
            self.geom_node.add_geom(self.geom)
        else:
            self.geom = self.geom_node.modify_geom(0)
            self.__make_points(vertices, colours, self.geom)