Esempio n. 1
0
    def _get_size(self):
        """Return the (width, height) for this Image.

        Returns:
            Tuple[int, int]: The (width, height) of this Image
        """
        w = ffi.new("int *")
        h = ffi.new("int *")
        lib.TCOD_image_get_size(self.image_c, w, h)
        return w[0], h[0]
Esempio n. 2
0
 def __init__(
     self,
     dimensions: int,
     algorithm: int = 2,
     implementation: int = SIMPLE,
     hurst: float = 0.5,
     lacunarity: float = 2.0,
     octaves: float = 4,
     seed: Optional[tcod.random.Random] = None,
 ):
     if not 0 < dimensions <= 4:
         raise ValueError("dimensions must be in range 0 < n <= 4, got %r" %
                          (dimensions, ))
     self._random = seed
     _random_c = seed.random_c if seed else ffi.NULL
     self._algorithm = algorithm
     self.noise_c = ffi.gc(
         ffi.cast(
             "struct TCOD_Noise*",
             lib.TCOD_noise_new(dimensions, hurst, lacunarity, _random_c),
         ),
         lib.TCOD_noise_delete,
     )
     self._tdl_noise_c = ffi.new("TDLNoise*",
                                 (self.noise_c, dimensions, 0, octaves))
     self.implementation = implementation  # sanity check
Esempio n. 3
0
    def __init__(self, width, height, order="C"):
        self._key_color = None
        self._ch = np.full((height, width), 0x20, dtype=np.intc)
        self._fg = np.zeros((height, width), dtype="(3,)u1")
        self._bg = np.zeros((height, width), dtype="(3,)u1")
        self._order = tcod._internal.verify_order(order)

        # libtcod uses the root console for defaults.
        bkgnd_flag = alignment = 0
        if lib.TCOD_ctx.root != ffi.NULL:
            bkgnd_flag = lib.TCOD_ctx.root.bkgnd_flag
            alignment = lib.TCOD_ctx.root.alignment

        self._console_data = self.console_c = ffi.new(
            "struct TCOD_Console*",
            {
                "w": width,
                "h": height,
                "ch_array": ffi.cast("int*", self._ch.ctypes.data),
                "fg_array": ffi.cast("TCOD_color_t*", self._fg.ctypes.data),
                "bg_array": ffi.cast("TCOD_color_t*", self._bg.ctypes.data),
                "bkgnd_flag": bkgnd_flag,
                "alignment": alignment,
                "fore": (255, 255, 255),
                "back": (0, 0, 0),
            },
        )
Esempio n. 4
0
 def _setstate_old(self, state):
     self._random = state[0]
     self.noise_c = ffi.new('struct TCOD_Noise*')
     self.noise_c.ndim = state[3]
     ffi.buffer(self.noise_c.map)[:] = state[4]
     ffi.buffer(self.noise_c.buffer)[:] = state[5]
     self.noise_c.H = state[6]
     self.noise_c.lacunarity = state[7]
     ffi.buffer(self.noise_c.exponent)[:] = state[8]
     if state[9]:
         # high change of this being prematurely garbage collected!
         self.__waveletTileData = ffi.new('float[]', 32 * 32 * 32)
         ffi.buffer(self.__waveletTileData)[:] = state[9]
     self.noise_c.noise_type = state[10]
     self._tdl_noise_c = ffi.new(
         'TDLNoise*', (self.noise_c, self.noise_c.ndim, state[1], state[2]))
Esempio n. 5
0
    def __init__(self, width, height, order='C'):
        self._key_color = None
        self._ch = np.zeros((height, width), dtype=np.intc)
        self._fg = np.zeros((height, width), dtype='(3,)u1')
        self._bg = np.zeros((height, width), dtype='(3,)u1')
        self._order = tcod._internal.verify_order(order)

        # libtcod uses the root console for defaults.
        bkgnd_flag = alignment = 0
        if lib.TCOD_ctx.root != ffi.NULL:
            bkgnd_flag = lib.TCOD_ctx.root.bkgnd_flag
            alignment = lib.TCOD_ctx.root.alignment

        self._console_data = self.console_c = ffi.new(
            'struct TCOD_Console*',
            {
                'w': width,
                'h': height,
                'ch_array': ffi.cast('int*', self._ch.ctypes.data),
                'fg_array': ffi.cast('TCOD_color_t*', self._fg.ctypes.data),
                'bg_array': ffi.cast('TCOD_color_t*', self._bg.ctypes.data),
                'bkgnd_flag': bkgnd_flag,
                'alignment': alignment,
                'fore': (255, 255, 255),
                'back': (0, 0, 0),
            },
        )
Esempio n. 6
0
 def __as_cdata(self):
     return ffi.new('struct TCOD_Map*', (
         self.width,
         self.height,
         self.width * self.height,
         ffi.cast('struct TCOD_MapCell*', self.__buffer.ctypes.data),
     ))
Esempio n. 7
0
 def __as_cdata(self):
     return ffi.new('map_t *', (
         self.width,
         self.height,
         self.width * self.height,
         ffi.cast('cell_t*', self.__buffer.ctypes.data),
     ))
Esempio n. 8
0
 def __setstate__(self, state: Any) -> None:
     """Create a new cdata object with the stored paramaters."""
     try:
         cdata = state["random_c"]
     except KeyError:  # old/deprecated format
         cdata = state["cdata"]
         del state["cdata"]
     state["random_c"] = ffi.new("mersenne_data_t*", cdata)
     self.__dict__.update(state)
Esempio n. 9
0
 def __setstate__(self, state):
     """Create a new cdata object with the stored paramaters."""
     try:
         cdata = state['random_c']
     except KeyError: # old/deprecated format
         cdata = state['cdata']
         del state['cdata']
     state['random_c'] = ffi.new('mersenne_data_t*', cdata)
     self.__dict__.update(state)
Esempio n. 10
0
    def blit(self,
             dest,
             dest_x=0,
             dest_y=0,
             src_x=0,
             src_y=0,
             width=0,
             height=0,
             fg_alpha=1.0,
             bg_alpha=1.0,
             key_color=None):
        """Blit from this console onto the ``dest`` console.

        Args:
            dest (Console): The destintaion console to blit onto.
            dest_x (int): Leftmost coordinate of the destintaion console.
            dest_y (int): Topmost coordinate of the destintaion console.
            src_x (int): X coordinate from this console to blit, from the left.
            src_y (int): Y coordinate from this console to blit, from the top.
            width (int): The width of the region to blit.

                If this is 0 the maximum possible width will be used.
            height (int): The height of the region to blit.

                If this is 0 the maximum possible height will be used.
            fg_alpha (float): Foreground color alpha vaule.
            bg_alpha (float): Background color alpha vaule.
            key_color (Optional[Tuple[int, int, int]]):
                None, or a (red, green, blue) tuple with values of 0-255.

        .. versionchanged:: 4.0
            Parameters were rearraged and made optional.

            Previously they were:
            `(x, y, width, height, dest, dest_x, dest_y, *)`
        """
        # The old syntax is easy to detect and correct.
        if hasattr(src_y, 'console_c'):
            src_x, src_y, width, height, dest, dest_x, dest_y = \
                dest, dest_x, dest_y, src_x, src_y, width, height
            warnings.warn(
                "Parameter names have been moved around, see documentation.",
                DeprecationWarning,
                stacklevel=2,
            )

        if key_color or self._key_color:
            key_color = ffi.new('TCOD_color_t*', key_color)
            lib.TCOD_console_blit_key_color(self.console_c, src_x, src_y,
                                            width, height, dest.console_c,
                                            dest_x, dest_y, fg_alpha, bg_alpha,
                                            key_color)
        else:
            lib.TCOD_console_blit(self.console_c, src_x, src_y, width, height,
                                  dest.console_c, dest_x, dest_y, fg_alpha,
                                  bg_alpha)
Esempio n. 11
0
    def __setstate__(self, state: Any) -> None:
        if isinstance(state, tuple):  # deprecated format
            return self._setstate_old(state)
        # unpack wavelet tile data if it exists
        if "_waveletTileData" in state:
            state["_waveletTileData"] = ffi.new("float[]",
                                                state["_waveletTileData"])
            state["noise_c"]["waveletTileData"] = state["_waveletTileData"]
        else:
            state["noise_c"]["waveletTileData"] = ffi.NULL

        # unpack TCOD_Noise and link to Random instance
        state["noise_c"]["rand"] = state["_random"].random_c
        state["noise_c"] = ffi.new("struct TCOD_Noise*", state["noise_c"])

        # unpack TDLNoise and link to libtcod noise
        state["_tdl_noise_c"]["noise"] = state["noise_c"]
        state["_tdl_noise_c"] = ffi.new("TDLNoise*", state["_tdl_noise_c"])
        self.__dict__.update(state)
Esempio n. 12
0
 def __as_cdata(self) -> Any:
     return ffi.new(
         "struct TCOD_Map*",
         (
             self.width,
             self.height,
             self.width * self.height,
             ffi.cast("struct TCOD_MapCell*", self.__buffer.ctypes.data),
         ),
     )
Esempio n. 13
0
    def __setstate__(self, state):
        if isinstance(state, tuple):  # deprecated format
            return self._setstate_old(state)
        # unpack wavelet tile data if it exists
        if '_waveletTileData' in state:
            state['_waveletTileData'] = ffi.new('float[]',
                                                state['_waveletTileData'])
            state['noise_c']['waveletTileData'] = state['_waveletTileData']
        else:
            state['noise_c']['waveletTileData'] = ffi.NULL

        # unpack TCOD_Noise and link to Random instance
        state['noise_c']['rand'] = state['_random'].random_c
        state['noise_c'] = ffi.new('struct TCOD_Noise*', state['noise_c'])

        # unpack TDLNoise and link to libtcod noise
        state['_tdl_noise_c']['noise'] = state['noise_c']
        state['_tdl_noise_c'] = ffi.new('TDLNoise*', state['_tdl_noise_c'])
        self.__dict__.update(state)
Esempio n. 14
0
 def get_path(self, x: int, y: int) -> List[Tuple[int, int]]:
     """Return a list of (x, y) steps to reach the goal point, if possible.
     """
     lib.TCOD_dijkstra_path_set(self._path_c, x, y)
     path = []
     pointer_x = ffi.new("int[2]")
     pointer_y = pointer_x + 1
     while lib.TCOD_dijkstra_path_walk(self._path_c, pointer_x, pointer_y):
         path.append((pointer_x[0], pointer_y[0]))
     return path
Esempio n. 15
0
 def __setstate__(self, state):
     self._key_color = None
     self.__dict__.update(state)
     self._console_data.update(
         {
         'ch_array': ffi.cast('int*', self._ch.ctypes.data),
         'fg_array': ffi.cast('TCOD_color_t*', self._fg.ctypes.data),
         'bg_array': ffi.cast('TCOD_color_t*', self._bg.ctypes.data),
         }
     )
     self._console_data = self.console_c = ffi.new(
         'struct TCOD_Console*', self._console_data)
Esempio n. 16
0
 def __setstate__(self, state):
     self._key_color = None
     self.__dict__.update(state)
     self._console_data.update(
         {
             "ch_array": ffi.cast("int*", self._ch.ctypes.data),
             "fg_array": ffi.cast("TCOD_color_t*", self._fg.ctypes.data),
             "bg_array": ffi.cast("TCOD_color_t*", self._bg.ctypes.data),
         }
     )
     self._console_data = self.console_c = ffi.new(
         "struct TCOD_Console*", self._console_data
     )
Esempio n. 17
0
    def get_tcod_path_ffi(self) -> Tuple[Any, Any, Tuple[int, int]]:
        if len(self.shape) != 2:
            raise ValueError("Array must have a 2d shape, shape is %r" %
                             (self.shape, ))
        if self.dtype.type not in self._C_ARRAY_CALLBACKS:
            raise ValueError("dtype must be one of %r, dtype is %r" %
                             (self._C_ARRAY_CALLBACKS.keys(), self.dtype.type))

        array_type, callback = self._C_ARRAY_CALLBACKS[self.dtype.type]
        userdata = ffi.new(
            "struct PathCostArray*",
            (ffi.cast("char*", self.ctypes.data), self.strides),
        )
        return callback, userdata, self.shape
Esempio n. 18
0
    def get_tcod_path_ffi(self):
        if len(self.shape) != 2:
            raise ValueError('Array must have a 2d shape, shape is %r' %
                             (self.shape, ))
        if self.dtype.type not in self._C_ARRAY_CALLBACKS:
            raise ValueError('dtype must be one of %r, dtype is %r' %
                             (self._C_ARRAY_CALLBACKS.keys(), self.dtype.type))

        array_type, callback = \
            self._C_ARRAY_CALLBACKS[self.dtype.type]
        userdata = ffi.new(
            'PathCostArray*',
            (self.width, ffi.cast(array_type, self.ctypes.data)),
        )
        return callback, userdata, self.width, self.height
Esempio n. 19
0
    def __init__(
        self,
        width: int,
        height: int,
        order: str = "C",
        buffer: Optional[np.array] = None,
    ):
        self._key_color = None  # type: Optional[Tuple[int, int, int]]
        self._order = tcod._internal.verify_order(order)
        if buffer is not None:
            if self._order == "F":
                buffer = buffer.transpose()
            self._ch = np.ascontiguousarray(buffer["ch"], np.intc)
            self._fg = np.ascontiguousarray(buffer["fg"], "u1")
            self._bg = np.ascontiguousarray(buffer["bg"], "u1")
        else:
            self._ch = np.ndarray((height, width), dtype=np.intc)
            self._fg = np.ndarray((height, width), dtype=self._DTYPE_RGB)
            self._bg = np.ndarray((height, width), dtype=self._DTYPE_RGB)

        # libtcod uses the root console for defaults.
        default_bg_blend = 0
        default_alignment = 0
        if lib.TCOD_ctx.root != ffi.NULL:
            default_bg_blend = lib.TCOD_ctx.root.bkgnd_flag
            default_alignment = lib.TCOD_ctx.root.alignment

        self._console_data = self.console_c = ffi.new(
            "struct TCOD_Console*",
            {
                "w": width,
                "h": height,
                "ch_array": ffi.cast("int*", self._ch.ctypes.data),
                "fg_array": ffi.cast("TCOD_color_t*", self._fg.ctypes.data),
                "bg_array": ffi.cast("TCOD_color_t*", self._bg.ctypes.data),
                "bkgnd_flag": default_bg_blend,
                "alignment": default_alignment,
                "fore": (255, 255, 255),
                "back": (0, 0, 0),
            },
        )

        if buffer is None:
            self.clear()
Esempio n. 20
0
    def __setstate__(self, state: Any) -> None:
        self._key_color = None
        if "_tiles" not in state:
            tiles = np.ndarray((self.height, self.width), dtype=self.DTYPE)
            tiles["ch"] = state["_ch"]
            tiles["fg"][..., :3] = state["_fg"]
            tiles["fg"][..., 3] = 255
            tiles["bg"][..., :3] = state["_bg"]
            tiles["bg"][..., 3] = 255
            state["_tiles"] = tiles
            del state["_ch"]
            del state["_fg"]
            del state["_bg"]

        self.__dict__.update(state)
        self._console_data["tiles"] = ffi.cast("struct TCOD_ConsoleTile*",
                                               self._tiles.ctypes.data)
        self._console_data = self.console_c = ffi.new("struct TCOD_Console*",
                                                      self._console_data)
Esempio n. 21
0
    def get_path(self, start_x, start_y, goal_x, goal_y):
        """Return a list of (x, y) steps to reach the goal point, if possible.

        Args:
            start_x (int): Starting X position.
            start_y (int): Starting Y position.
            goal_x (int): Destination X position.
            goal_y (int): Destination Y position.
        Returns:
            List[Tuple[int, int]]:
                A list of points, or an empty list if there is no valid path.
        """
        lib.TCOD_path_compute(self._path_c, start_x, start_y, goal_x, goal_y)
        path = []
        x = ffi.new('int[2]')
        y = x + 1
        while lib.TCOD_path_walk(self._path_c, x, y, False):
            path.append((x[0], y[0]))
        return path
Esempio n. 22
0
 def __init__(self, dimensions, algorithm=2, implementation=SIMPLE,
              hurst=0.5, lacunarity=2.0, octaves=4, seed=None):
     if not 0 < dimensions <= 4:
         raise ValueError('dimensions must be in range 0 < n <= 4, got %r' %
                          (dimensions,))
     self._random = seed
     _random_c = seed.random_c if seed else ffi.NULL
     self._algorithm = algorithm
     self.noise_c = ffi.gc(
         ffi.cast(
             'perlin_data_t*',
             lib.TCOD_noise_new(dimensions, hurst, lacunarity,
                                _random_c),
             ),
         lib.TCOD_noise_delete)
     self._tdl_noise_c = ffi.new('TDLNoise*', (self.noise_c,
                                               dimensions,
                                               0,
                                               octaves))
     self.implementation = implementation # sanity check