Skip to content
Snippets Groups Projects
drawing.py 41.6 KiB
Newer Older
  • Learn to ignore specific revisions
  •             start=0,
                stop=np.max(positions[:, 0]),
                num=len(unique_x_vals),
            )
            replace_map = {
                unique_x_vals[i]: new_positions_unique[i] for i in range(len(unique_x_vals))
            }
            for k, v in graph_dict["layout"].items():
                graph_dict["layout"][k] = (replace_map[v[0]], v[1])
    
    
            positions = np.array(list(positions_dict.values()))
            positions = positions - positions.min(axis=0)
            positions[positions == 0] = 0.000001
            positions = (
    
                positions / positions.max(axis=0) * (np.array([width, height]) - node_size)
    
            positions += node_size / 2
    
            positions_dict = {
                name: pos for name, pos in zip(positions_dict.keys(), positions)
            }
    
    
            for start, end in graph_dict["edges"]:
                pygame.draw.line(
                    screen,
                    "black",
                    positions_dict[start],
                    positions_dict[end],
                    width=5,
                )
            for name, pos in positions_dict.items():
                key = name.split("_")[0]
    
                if key in [
                    "Chips",
                    "FriedFish",
                    "Burger",
                    "Salad",
                    "TomatoSoup",
                    "OnionSoup",
                    "FishAndChips",
                    "Pizza",
                ]:
                    self.draw_thing(
                        screen,
                        np.array(pos),
                        self.config["Plate"]["parts"],
    
                        absolute_size=node_size,
    
                    )
                if "Soup" in key:
                    self.draw_thing(
                        screen,
                        np.array(pos),
                        self.config[key + "Plate"]["parts"],
    
                    )
                else:
                    viz = self.config[key]["parts"]
    
                    self.draw_thing(screen, np.array(pos), viz, absolute_size=node_size, absolute=True)
    
    
    def save_screenshot(state: dict, config: dict, filename: str | Path) -> None:
    
    Fabian Heinrich's avatar
    Fabian Heinrich committed
        """Standalone function to save a screenshot. Creates a visualizer from the config and visualizes
        the game state, saves it to the given filename.
    
        Args:
            state: The gamestate to visualize.
            config: Visualization config for the visualizer.
            filename: Filename to save the image to.
    
        """
    
        vis = Visualizer(config)
        vis.create_player_colors(len(state["players"]))
        vis.set_grid_size(40)
    
    
    
        screen = vis.draw_gamescreen(state, [0])
        pygame.image.save(screen, filename)
    
    def generate_recipe_images(config: dict, folder_path: str | Path):
        os.makedirs(ROOT_DIR / folder_path, exist_ok=True)
        env = Environment(
    
            env_config=str(ROOT_DIR / "configs" / "environment_config.yaml"),
            layout_config=str(ROOT_DIR / "configs" / "layouts" / "basic.layout"),
            item_info=str(ROOT_DIR / "configs" / "item_info.yaml"),
    
            as_files=True,
            env_name="0",
        )
    
        viz = Visualizer(config)
        pygame.init()
        pygame.font.init()
    
    
        graph_dicts = env.recipe_validation.get_recipe_graphs()
    
        width, height, node_size = 700, 400, 80
        flags = pygame.HIDDEN
    
        for graph_dict in graph_dicts:
    
            screen = pygame.display.set_mode((width, height), flags=flags)
    
            viz.draw_recipe_image(screen, graph_dict, width, height, node_size)
    
            pygame.image.save(screen, f"{folder_path}/{graph_dict['meal']}.png")
    
    def main(cli_args):
    
        """Runs the Cooperative Cuisine Image Generation process.
    
        This method takes command line arguments to specify the state file, visualization configuration file, and output
        file for the generated image. It then reads the visualization configuration file and state file, and calls the
        'save_screenshot' and 'generate_recipe_images' methods to generate the image.
    
    
        Args:
            -s, --state: A command line argument of type `argparse.FileType("r", encoding="UTF-8")`. Specifies the state file to use for image generation. If not provided, the default value is 'ROOT_DIR / "pygame_2d_vis" / "sample_state.json"'.
    
            -v, --visualization_config: A command line argument of type `argparse.FileType("r", encoding="UTF-8")`. Specifies the visualization configuration file to use for image generation. If not provided, the default value is 'ROOT_DIR / "pygame_2d_vis" / "visualization.yaml"'.
    
            -o, --output_file: A command line argument of type `str`. Specifies the output file path for the generated image. If not provided, the default value is 'ROOT_DIR / "generated" / "screenshot.jpg"'.
        """
    
    
        with open(cli_args.visualization_config, "r") as f:
    
            viz_config = yaml.safe_load(f)
    
        with open(cli_args.state, "r") as f:
    
            state = json.load(f)
    
        save_screenshot(state, viz_config, cli_args.output_file)
        generate_recipe_images(viz_config, cli_args.output_file.parent)
    
        parser = argparse.ArgumentParser(
    
            prog="Cooperative Cuisine Image Generation",
    
            description="Generate images for a state in json.",
    
            epilog="For further information, see https://scs.pages.ub.uni-bielefeld.de/cocosy/cooperative-cuisine/overcooked_simulator.html",
    
        create_screenshot_parser(parser)
    
        args = parser.parse_args()
        main(args)