Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Get/Set compound members of ftype objects

31 views
Skip to first unread message

Deepankar Sharma

unread,
Sep 14, 2024, 3:50:28 AM9/14/24
to chez-scheme
Given the following types

(define-ftype Vector2
    (struct
      [x float]
      [y float]))

(define-ftype Camera2D
    (struct
      [offset Vector2]
      [target Vector2]
      [rotation float]
      [zoom float]))

I have written a verbose camera constructor in the following way

(define (make-camera2d offset target rotation zoom)
    ;; params:
    ;;      offset: Vector2
    ;;      target: Vector2
    ;;      rotation: float
    ;;      zoom: float
    (let* ((c (make-ftype-pointer Camera2D (foreign-alloc (ftype-sizeof Camera2D))))
           (offset-x (ftype-&ref Camera2D (offset x) c))
           (offset-y (ftype-&ref Camera2D (offset y) c))
           (target-x (ftype-&ref Camera2D (target x) c))
           (target-y (ftype-&ref Camera2D (target y) c)))

      (ftype-set! float () offset-x (ftype-ref Vector2 (x) offset))
      (ftype-set! float () offset-y (ftype-ref Vector2 (y) target))

      (ftype-set! float () target-x (ftype-ref Vector2 (x) offset))
      (ftype-set! float () target-y (ftype-ref Vector2 (y) offset))

      (ftype-set! Camera2D (rotation) c (inexact rotation))
      (ftype-set! Camera2D (zoom) c (inexact zoom))
      (register-object c finalizer)
      c))


I would like to be able to write something similar to this where I am setting compound fields of Camera2D in one go.

(define (make-camera2d offset target rotation zoom)
    ;; params:
    ;;      offset: Vector2
    ;;      target: Vector2
    ;;      rotation: float
    ;;      zoom: float
    (let* ((c (make-ftype-pointer Camera2D (foreign-alloc (ftype-sizeof Camera2D)))))
     
      ;; Want to be able to set compounds of plain old data types directly
      ;; without having to delve into doing them field by field.
      (ftype-set! Camera2D (offset) c offset)
      (ftype-set! Camera2D (target) c target)

      (ftype-set! Camera2D (rotation) c (inexact rotation))
      (ftype-set! Camera2D (zoom) c (inexact zoom))
      (register-object c finalizer)
      c))

Similarly on the read side, would like to be able to do
(ftype-ref Camera2D (offset) c)

Any pointers on how to achieve this or general advice on how to make the above more terse. 

Regards,
Deepankar
Reply all
Reply to author
Forward
0 new messages