Ejemplo n.º 1
0
    def __init__(self,
                 camera_gear,
                 P_arr=np.array([[0., 0., 0.], [0., 1., 1.], [0., 0, 1.],
                                 [1., 1., 1.]])):

        BezierCurve.__init__(self, P_arr, **kwargs)

        self.camera_gear = camera_gear
        # self.camera_gear.set_view_to_yz_plane()

        # --- plot draggable bezier curve together with points
        # for dragging the points and updating the bezier curve,
        # the points have to stay instantiated (objects that are dragged), while the bezier curve
        # can be regenerated from the new point positions at every drag event

        # -- add picking utilities
        self.pom = PickableObjectManager()
        self.dragAndDropObjectsManager = DragAndDropObjectsManager()
        self.collisionPicker = CollisionPicker(
            self.camera_gear, engine.tq_graphics_basics.tq_render,
            base.mouseWatcherNode, self.dragAndDropObjectsManager)

        # -- add a mouse task to check for picking
        self.p3d_direct_object = DirectObject.DirectObject()
        self.p3d_direct_object.accept('mouse1',
                                      self.collisionPicker.onMouseTask)

        # -- add the PickablePoints
        self.control_points_pickable_points = []

        # ---- go through the coordinates and assign PickablePoints
        for p in self.bez_points:
            pt = PickablePoint(self.pom, pos=Vec3(*p))

            pt_dragger = PickablePointDragger(pt, self.camera_gear)
            pt_dragger.add_on_state_change_function(sayhi)
            pt_dragger.add_on_state_change_function(
                self.updateCurveAfterPointCoordsChanged)

            self.dragAndDropObjectsManager.add_dragger(pt_dragger)

            pt.setHpr(90, 0, 0)  # 90 degrees yaw
            pt.showBounds()

            self.control_points_pickable_points.append(pt)

        # -- add a line betwen each set of 2 pickablepoints (like in inkscape)
        # ---- with only 4 pickablepoints, assign a line to the fist 2 and the last 2
        self.l1 = Line1dSolid(thickness=1., color=Vec4(1, 0, 1, 1))
        self.l2 = Line1dSolid(thickness=1., color=Vec4(1, 0, 1, 1))

        self.updateCurveAfterPointCoordsChanged()
Ejemplo n.º 2
0
    def update_line(self, update_graphics=True):
        """ set the line to the appropriate dimensions """
        if self.line is None:
            self.line = Line1dSolid()
            self.line.reparentTo(self)

        if update_graphics == True:
            self.line.setTipPoint(self.get_v1())
            self.line.setTailPoint(self.get_v2())
Ejemplo n.º 3
0
    def __init__(self,
                 pos_vec3=Vec3(0., 0., 0.),
                 width=1.0,
                 height=1.0,
                 **kwargs):
        """
        Args:
            pos_vec3: upper left corner in p3d coordinates in aspect2d
                      (+x is right, +z is up, y has to be 0.)
            **kwargs:
                TQGraphicsNodePath_creation_parent_node: aspect2d or render
                thickness: thickness of the lines in the quad
        """

        self.pos_vec3 = None
        self.width = None
        self.height = None

        TQGraphicsNodePath.__init__(self)

        self.set_pos_vec3(pos_vec3)

        self.border_line_top = Line1dSolid(**kwargs)
        self.border_line_top.reparentTo(self)

        self.border_line_bottom = Line1dSolid(**kwargs)
        self.border_line_bottom.reparentTo(self)

        self.border_line_left = Line1dSolid(**kwargs)
        self.border_line_left.reparentTo(self)

        self.border_line_right = Line1dSolid(**kwargs)
        self.border_line_right.reparentTo(self)

        self.b2d = Box2d()  # background box
        self.b2d.reparentTo(self)
        self.b2d.setColor(Quad.bg_color, 1)

        self.set_border_color(Quad.border_color, 1)

        self.set_width(width)
        self.set_height(height)
Ejemplo n.º 4
0
    def __init__(self, edge_graphics, camera_gear):
        """ """
        # register event for onmousemove
        self.edge_graphics = edge_graphics
        self.camera_gear = camera_gear

        taskMgr.add(self.mouseMoverTask, 'mouseMoverTask')

        self.shortest_distance_line = Line1dSolid(thickness=2, color=Vec4(1., 0., 1., 0.5))
        self.shortest_distance_line.reparentTo(edge_graphics)

        self.init_time_label()
Ejemplo n.º 5
0
    def plot(self):
        # nodes
        for coord in self.coords:
            p = Point3d(
                pos=Vec3(coord[0], coord[1], 0.),
                scale=0.025)
            self.graph_points.append(p)

        # edges
        for edge in self.edges_list:
            point1 = self.pos[edge[0]]
            point2 = self.pos[edge[1]]

            # plot a line between point1 and point2
            edgeline = Line1dSolid()
            edgeline.setTailPoint(Vec3(point1[0], point1[1], 0.))
            edgeline.setTipPoint(Vec3(point2[0], point2[1], 0.))
Ejemplo n.º 6
0
    def __init__(self, draggablegraph, cameragear):
        # register event for onmousemove
        self.draggablegraph = draggablegraph
        self.cameragear = cameragear
        # self.mouse = mouse

        taskMgr.add(self.mouseMoverTask, 'mouseMoverTask')
        base.accept('mouse1', self.onPress)

        self.hoverindicatorpoint = Point3d()

        # self.c1point = Point3d()

        # self.c2point = Point3d()

        self.shortest_distance_line = Line1dSolid(thickness=5, color=Vec4(1., 0., 1., 0.5))

        self.init_time_label()
Ejemplo n.º 7
0
    def __init__(self, done_function, position, size=0.2, frequency=1):
        """
        Args:
            done_function: function which controls when the waiting symbol
                           animation should be stopped (when True)
            position: Vec3 of the upper left hand corner in p3d coordinates """

        # -- logical
        self.done_function = done_function

        self.position = position
        self.size = size
        self.frequency = frequency
        self.duration = 1.

        self.a = None

        TQGraphicsNodePath.__init__(self)

        # -- supporting graphics
        self.quad = Quad(thickness=3.0,
                         TQGraphicsNodePath_creation_parent_node=engine.
                         tq_graphics_basics.tq_aspect2d)
        self.quad.reparentTo(self)

        self.quad.set_pos_vec3(self.position)
        self.quad.set_height(self.size)
        self.quad.set_width(self.size)

        self.line = Line1dSolid(thickness=3.0,
                                TQGraphicsNodePath_creation_parent_node=engine.
                                tq_graphics_basics.tq_aspect2d)
        self.line.reparentTo(self)

        self.anim_seq = Sequence()

        self.anim_seq.set_sequence_params(
            duration=self.duration,
            extraArgs=[],
            update_function=self.update,
            on_finish_function=self.restart_animation)

        self.anim_seq.start()
Ejemplo n.º 8
0
    def update_line(self, update_graphics=True):
        """ set the line to the appropriate dimensions """
        if self.line is None:
            self.line = Line1dSolid()
            self.line.reparentTo(self)

        from interactive_tools.draggables import DraggablePoint

        if self.dp1 is None:
            self.dp1 = DraggablePoint(self.camera_gear)
            self.dp1.reparentTo(self)

        if self.dp2 is None:
            self.dp2 = DraggablePoint(self.camera_gear)
            self.dp2.reparentTo(self)

        if update_graphics == True:
            self.line.setTipPoint(self.get_inset_v1())
            self.line.setTailPoint(self.get_inset_v2())
            # self.dp1.setPos(self.get_dp1_v1())
            # self.dp2.setPos(self.get_dp2_v2())
            self.dp1.setPos(self.get_v1())
            self.dp2.setPos(self.get_v2())
Ejemplo n.º 9
0
    def updateTubeMesh(self):
        # -- re-calculate the points and path lengths
        points, path_lengths = math_utils.getPointsAndPathLengthsAlongPolygonalChain(
            func=(
                lambda t: np.array([
                    BezierCurve.calcBezierCurve(t, self.bez_points)[0],
                    BezierCurve.calcBezierCurve(t, self.bez_points)[1],
                    BezierCurve.calcBezierCurve(t, self.bez_points)[2]
                ])
                # lambda t: np.array([0, t, 2.7**t])
            ),
            param_interv=np.array([0., 1.]),
            ed_subpath_length=0.2)

        # ---- clear out the ancillary objects on update
        for pp in self.point_primitives:
            pp.removeNode()

        for oc in self.oriented_circles:
            oc.removeNode()

        for tv in self.tangent_vectors:
            tv.removeNode()

        for nv in self.normal_vectors:
            nv.removeNode()

        for bv in self.binormal_vectors:
            bv.removeNode()

        for mp in self.mesh_points:
            mp.removeNode()

        # ---- then re-generate them anew
        self.point_primitives = []
        self.oriented_circles = []

        self.tangent_vectors = []
        self.tangent_vectors_logical = []
        self.normal_vectors = []
        self.binormal_vectors = []

        self.mesh_points = []
        self.mesh_points_logical = [
        ]  # stores the 3d vertex positions of the desired triangle mesh

        # ---- for the tube mesh

        # circles_vertices = []  # stores the 3d vertex positions of the desired triangle mesh
        triangles = [
        ]  # stores the indices to the vertices in circles_vertices
        radius = 0.1
        num_of_verts = 10
        scale = 0.2

        for i, p in enumerate(points):
            self.point_primitives.append(PointPrimitive(pos=Vec3(*tuple(p))))
            t_vec = None
            if i > 0:
                d_vec_r_of_s = points[i] - points[i - 1]
                d_s = np.linalg.norm(path_lengths[i] - path_lengths[i - 1])
                t_vec = math_utils.normalize(d_vec_r_of_s / d_s)

                tv_line = Line1dSolid(color=Vec4(1., 0., 0., 1.))
                tv_line.setTipPoint(points[i] + t_vec * scale)
                tv_line.setTailPoint(points[i])

                tv_line.hide()

                self.tangent_vectors.append(tv_line)
                self.tangent_vectors_logical.append(t_vec)

                # --- draw oriented circle
                oc = OrientedCircle(origin_point=points[i],
                                    normal_vector=Vec3(*tuple(t_vec)),
                                    radius=radius)

                oc.hide()

                self.oriented_circles.append(oc)

                # --- generate vertex data for the current circle
                vd_cc = math_utils.get_circle_vertices(
                    num_of_verts=num_of_verts, radius=radius)
                vd_cc_transformed = []
                for v in vd_cc:
                    # transform the vertices of the circles appropriately (you want one mesh)
                    trafo = math_utils.p3d_mat4_to_math_convention(
                        math_utils.getTranslationMatrix4x4_forrowvecs(
                            v[0], v[1], v[2]) *
                        OrientedCircle.getSetupTransformation(
                            t_vec, points[i], scale=0.5))

                    # transform the coordinates
                    v = glm.vec4(*tuple(v),
                                 1.) * glm.mat4(*tuple(np.ravel(trafo)))

                    vd_cc_transformed.append([v[0], v[1], v[2]])

                    point = Point3d(pos=np.array([v[0], v[1], v[2]]),
                                    scale=0.02)
                    point.hide()

                    self.mesh_points.append(point)

                self.mesh_points_logical.append(vd_cc_transformed)

            if i > 1:  # after a change in the tangent vector, the normal vector is well-defined
                n_vec = math_utils.normalize(
                    self.tangent_vectors_logical[i - 1] -
                    self.tangent_vectors_logical[i - 2])

                nv_line = Line1dSolid(color=Vec4(0., 1., 0., 1.))
                nv_line.setTipPoint(points[i] + n_vec * scale)
                nv_line.setTailPoint(points[i])

                self.normal_vectors.append(nv_line)

                # after tangent vector and normal vector are well-defined, the binormal is also
                b_vec = math_utils.normalize(np.cross(n_vec, t_vec))

                bv_line = Line1dSolid(color=Vec4(0., 0., 1., 1.))
                bv_line.setTipPoint(points[i] + b_vec * scale)
                bv_line.setTailPoint(points[i])

                self.binormal_vectors.append(bv_line)

                # you can generate vertex and index data for the current circle and a last circle

                # ---- access vertex data of the previous circle

                vd_pc = self.mesh_points_logical[i - 2]

                vd_pc_idx_offset = (i - 2) * num_of_verts
                vd_cc_idx_offset = (i - 1) * num_of_verts

                # now build the triangles (indices) to go in between the last circle
                # and the current circle
                j = 0  # vertex index
                cur_triangles_arr = []  # stores 3-arrays of indices
                while j < len(vd_pc) - 1:
                    # sense of contour buildup: clockwise

                    # 1st triangle
                    cur_triangles_arr.append([
                        vd_pc_idx_offset + j, vd_cc_idx_offset + j,
                        vd_pc_idx_offset + j + 1
                    ])

                    # opposite side triangle
                    cur_triangles_arr.append([
                        vd_pc_idx_offset + j + 1, vd_cc_idx_offset + j,
                        vd_cc_idx_offset + j + 1
                    ])

                    j += 1

                triangles.append(cur_triangles_arr)

        # -- plot the mesh whose points and Tristrips were created

        vertices_flat = np.ravel(self.mesh_points_logical)
        indices_flat = np.ravel(triangles)

        gn = create_Triangle_Mesh_From_Vertices_and_Indices(vertices_flat,
                                                            indices_flat,
                                                            color_vec4=Vec4(
                                                                1., 0., 0.,
                                                                1.))
        # gn = createCircle(num_of_verts=100)
        # gn = createColoredUnitQuadGeomNode(color_vec4=Vec4(0., 0., 1., 1.),
        #                                    center_it=False)

        if self.tube_mesh_nodepath:
            self.tube_mesh_nodepath.removeNode()

        self.tube_mesh_nodepath = self.getParent_p3d().attachNewNode_p3d(gn)
        self.tube_mesh_nodepath.setRenderModeWireframe()
        self.tube_mesh_nodepath.setTwoSided(True)
        self.tube_mesh_nodepath.setLightOff(1)
Ejemplo n.º 10
0
    def regenerate_ticks_graphics(self, num_arr, p3d_axis_length,
                                  axis_direction_index):
        """ pass an array, generate a bunch of vertical lines """
        self.remove_ticks_graphics()
        self.num_arrs[axis_direction_index] = num_arr

        for c_num in num_arr:
            pos = Ticks.get_tick_pos_along_axis(p3d_axis_length, num_arr,
                                                c_num)

            if (np.abs(pos) == np.inf):
                print(
                    "warning: (np.abs(math_utils.p3d_to_np(pos)) == np.inf).any() == True: ",
                    "TODO: improve this mechanism!")
                # TODO: before updating the ticks check if the range
                # of the ticks is near zero. then set the minimum range
                # and center it around the middle
                return

            line = Line1dSolid(thickness=1.5)
            a = Vec3(pos, 0., self.tick_length / 2.)
            b = Vec3(pos, 0., -self.tick_length / 2.)

            # print("a: ", a)
            # print("b: ", b)
            line.setTipPoint(a)
            line.setTailPoint(b)

            label = None
            if axis_direction_index == 0:
                alignment = "center"
            if axis_direction_index == 1:
                alignment = "center"

            text_kwargs = dict(text="{:.1e}".format(c_num),
                               alignment=alignment)

            if self.update_labels_orientation == True:
                label = BasicOrientedText(
                    self.camera_gear,
                    update_orientation_on_camera_rotate=self.
                    update_labels_orientation,
                    **text_kwargs)
            else:
                # label = BasicText(**text_kwargs)
                # Basic2dText
                label = Basic2dText(rotate_angle_2d=0, **text_kwargs)

            label.showTightBounds()
            height = engine.tq_graphics_basics.get_pts_to_p3d_units(
                label.pointsize)
            width = (label.textNode.getWidth() /
                     label.textNode.getHeight()) * height

            # if self.update_labels_orientation == True:
            if axis_direction_index == 0:
                label.setPos(Vec3(pos, 0., -height * 1.5))
                # print("height: ", height, ", width: ", width)
            elif axis_direction_index == 1:  # y axis in 2d
                label.setPos(Vec3(pos - (height / 4.), 0., width))

                if self.attach_to_space == "render":
                    None  # do not rotate the label
                elif self.attach_to_space == "aspect2d":
                    h, p, r = aspect2d.getHpr()
                    label.setHpr(h, p, r + 90)
                else:
                    print(
                        "ERR: self.attach_to_space must be aspect2d or render")
                    exit(1)
            # else:
            #     if axis_direction_index==0:
            #         label.setPos(Vec3(pos, 0., -height*1.5))
            #         # print("height: ", height, ", width: ", width)
            #     elif axis_direction_index==1:
            #         label.setPos(Vec3(pos - (height/4.), 0., width))

            t = Tick()
            t.set_line(line)
            t.set_label(label)
            t.reparentTo(self)
            self.ticks.append(t)

            # re-face the camera again after being reparented to a tick, since
            # the relative orientation to render has changed by the reparenting
            # print("face camera")

            if self.update_labels_orientation == True:
                t.label.face_camera()
Ejemplo n.º 11
0
    def __init__(self, camera_gear, edge_player_recorder_spawner=None):

        self.camera_gear = camera_gear
        self.edge_player_recorder_spawner = edge_player_recorder_spawner

        self.state = EdgeRecorderState()

        # -- do geometry logic
        # make the line small, but pick initial direction

        # -- do graphics stuff
        tail_init_point = Vec3(0., 0., 0.)
        self.p_c = Point3dCursor()
        self.p_c.setPos(tail_init_point)
        self.p_c.reparentTo(self)

        self.line = Line1dSolid()
        tip_init_point = tail_init_point + Vec3(2., 2., 2.)

        self.line.setTipPoint(tip_init_point)
        self.line.setTailPoint(tail_init_point)

        # actions: record, pause, kill

        # setup the spacebar to continue/start recording or pausing
        self.space_direct_object = DirectObject.DirectObject()
        self.space_direct_object.accept('space', self.react_to_spacebar)

        self.set_recording_direct_object = DirectObject.DirectObject()
        self.set_recording_direct_object.accept('r', self.react_to_r)

        # -- do p3d sequence stuff
        # ---- initialize the sequence

        self.v1 = Vec3(0.5, 0.5, 0.)
        self.v_dir = Vec3(1., 1., 0.) / np.linalg.norm(Vec3(1., 1., 0.))

        self.extraArgs = [
            math_utils.p3d_to_np(self.v1),
            math_utils.p3d_to_np(self.v_dir), self.p_c, self.line
        ]

        self.init_recorder_label()

        self.cursor_sequence = Sequence()
        self.cursor_sequence.set_sequence_params(
            duration=EdgeRecorder.s_dur,
            extraArgs=self.extraArgs,
            update_function=self.update_while_moving_function,
            on_finish_function=self.on_finish_cursor_sequence)

        # --- additional ui stuff ---
        # -- init hover and click actions

        # self.edge_hoverer = EdgeHoverer(self, self.camera_gear)
        # self.edge_mouse_clicker = EdgeMouseClicker(self)

        # make a pinned label saying Rec. in thick red letters

        # --- set initial state ----

        self.set_stopped_at_beginning()

        self.recorder = Recorder()
Ejemplo n.º 12
0
    def update(self):
        """ resets the positions """

        orbit_center = math_utils.np_to_p3d_Vec3(
            self.camera_gear.get_orbit_center())

        if not self.l1o:
            self.l1o = Line1dSolid(thickness=self.crosshair_outer_thickness,
                                   color=self.crosshair_outer_color)
            self.l1o.reparentTo(self)
            self.l1o.set_render_above_all(True)

        self.l1o.setTailPoint(orbit_center -
                              Vec3(self.crosshair_outer_lines_length /
                                   2., 0., 0.))
        self.l1o.setTipPoint(orbit_center +
                             Vec3(self.crosshair_outer_lines_length /
                                  2., 0., 0.))

        if not self.l2o:
            self.l2o = Line1dSolid(thickness=self.crosshair_outer_thickness,
                                   color=self.crosshair_outer_color)
            self.l2o.reparentTo(self)
            self.l2o.set_render_above_all(True)

        self.l2o.setTailPoint(orbit_center -
                              Vec3(0., self.crosshair_outer_lines_length /
                                   2., 0.))
        self.l2o.setTipPoint(orbit_center +
                             Vec3(0., self.crosshair_outer_lines_length /
                                  2., 0.))

        if not self.l3o:
            self.l3o = Line1dSolid(thickness=self.crosshair_outer_thickness,
                                   color=self.crosshair_outer_color)
            self.l3o.reparentTo(self)
            self.l3o.set_render_above_all(True)

        self.l3o.setTailPoint(orbit_center -
                              Vec3(0., 0., self.crosshair_outer_lines_length /
                                   2.))
        self.l3o.setTipPoint(orbit_center +
                             Vec3(0., 0., self.crosshair_outer_lines_length /
                                  2.))

        if not self.l1i:
            self.l1i = Line1dSolid(thickness=self.crosshair_inner_thickness,
                                   color=self.crosshair_inner_color)
            self.l1i.set_render_above_all(True)
            self.l1i.reparentTo(self)

        self.l1i.setTailPoint(orbit_center -
                              Vec3(self.crosshair_inner_lines_length /
                                   2., 0., 0.))
        self.l1i.setTipPoint(orbit_center +
                             Vec3(self.crosshair_inner_lines_length /
                                  2., 0., 0.))

        if not self.l2i:
            self.l2i = Line1dSolid(thickness=self.crosshair_inner_thickness,
                                   color=self.crosshair_inner_color)
            self.l2i.set_render_above_all(True)
            self.l2i.reparentTo(self)

        self.l2i.setTailPoint(orbit_center -
                              Vec3(0., self.crosshair_inner_lines_length /
                                   2., 0.))
        self.l2i.setTipPoint(orbit_center +
                             Vec3(0., self.crosshair_inner_lines_length /
                                  2., 0.))

        if not self.l3i:
            self.l3i = Line1dSolid(thickness=self.crosshair_inner_thickness,
                                   color=self.crosshair_inner_color)
            self.l3i.set_render_above_all(True)
            self.l3i.reparentTo(self)

        self.l3i.setTailPoint(orbit_center -
                              Vec3(0., 0., self.crosshair_inner_lines_length /
                                   2.))
        self.l3i.setTipPoint(orbit_center +
                             Vec3(0., 0., self.crosshair_inner_lines_length /
                                  2.))
Ejemplo n.º 13
0
    def __init__(self,
                 tail_point_logical=None,
                 tip_point_logical=None,
                 arrowhead_scale=1. / 15.,
                 **kwargs):
        TQGraphicsNodePath.__init__(self, **kwargs)

        if 'linetype' in kwargs:
            self.linetype = kwargs.get('linetype')
        else:
            self.linetype = "1d"

        if 'color' in kwargs:
            self.color = kwargs.get('color')
        else:
            self.color = Vec4(1., 0., 0., 1.)

        if self.linetype == "1d":
            if 'thickness1dline' in kwargs:
                self.thickness1dline = kwargs.get('thickness1dline')
            else:
                self.thickness1dline = 2.

            if 'linestyle' in kwargs:
                self.linestyle = kwargs.get('linestyle')
            else:
                self.linestyle = "-"

            if self.linestyle == "--":
                howmany_periods = 5.
                if 'howmany_periods' in kwargs:
                    howmany_periods = kwargs.get('howmany_periods')

                self.line1 = Line1dDashed(thickness=self.thickness1dline,
                                          color=self.color,
                                          howmany_periods=howmany_periods)
            else:
                self.line1 = Line1dSolid(thickness=self.thickness1dline,
                                         color=self.color)
        elif self.linetype == "2d":
            self.line1 = Line2dObject()
        else:
            print("Error: linetype " + self.linetype + " is invalid")

        if 'arrowheadstyle' in kwargs:
            self.arrowheadstyle = kwargs.get('arrowheadstyle')
            if self.arrowheadstyle == "ArrowHeadCone":
                self.arrowhead = ArrowHeadCone()
            elif self.arrowheadstyle == "ArrowHeadConeShaded":
                self.arrowhead = ArrowHeadConeShaded(color=self.color)
            elif self.arrowheadstyle == "ArrowHead":
                self.arrowhead = ArrowHead()
        else:
            self.arrowhead = ArrowHeadConeShaded(color=self.color,
                                                 scale=arrowhead_scale)

        self.line1.reparentTo(self)
        self.arrowhead.reparentTo(self)

        self.tip_point_logical = tip_point_logical
        self.tail_point_logical = tail_point_logical

        if self.tip_point_logical is None or self.tail_point_logical is None:
            self.tip_point_logical = Vec3(0., 0., 0.)
            self.tail_point_logical = Vec3(0., 0., 0.)

        self.setTipPoint(self.tip_point_logical)
        self.setTailPoint(self.tail_point_logical)

        self.setColor(self.color)

        self.label = None  # usually it is not labelled