This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Find path to package resources?

3 posts · 1474 views

Good morning!

As in my last thread, I'm working on a small game using cl-sdl2. At this point I've got a playable demo and I'm working out a few kinks.

The biggest is loading images. I have a small routine that loads sprites from *.png files, and memoizes the resultant textures.
(defvar *sprites* nil)
(defun load-sprite (sprite-type renderer)
  (let* ((filename (concatenate 'string (symbol-name sprite-type) ".png"))
         (sprite (getf *sprites* sprite-type)))
    (unless sprite
      (setf sprite (sdl2:create-texture-from-surface renderer
                                                     (sdl2-image:load-image filename))
            (getf *sprites* sprite-type) sprite))
    sprite))
This routine works fine as long as the images are stored in the current path, but if I just start SLIME and eval, I get a path error. To get around that problem, I added this to the top of my source file initially:
(sb-posix:chdir #P"/home/jakykong/lisp/mouse")
This works, but it's obviously not going to allow the code to move around. If I'm using SLIME, it's doubly annoying since starting SLIME from the current directory is inconvenient.

As a first pass at figuring out a better way to locate resources, I looked in the ASDF documentation to see if there's a way to find the source path for the current package, and the closest I could get is:
(defun get-system-path (system)
  (asdf:component-pathname (asdf:find-system system)))
Which returns a path like #P"/home/jakykong/quicklisp/local-projects/name/"; I can either change directory there as before or use #'merge-pathnames when loading the image.

This feels like a hack that probably has pitfalls I'm not considering. Is there a more conventional way to locate external files?

Re: Find path to package resources?

I use ASDF:SYSTEM-RELATIVE-PATHNAME (usually with a per-package wrapper) to directly create PATHNAMES when I need to do this.

Re: Find path to package resources?

pjstirling wrote:I use ASDF:SYSTEM-RELATIVE-PATHNAME (usually with a per-package wrapper) to directly create PATHNAMES when I need to do this.
I hadn't spotted that function earlier. That's much cleaner. Thank you! :)