planetis-m / naylib

Yet another raylib Nim wrapper
MIT License
209 stars 11 forks source link

Model Shared Meshes, Shaders and Textures #58

Closed planetis-m closed 1 year ago

planetis-m commented 1 year ago

One idea was to use ref T, setMaterialTexture is:

proc setMaterialTexture*(material: var Material, mapType: MaterialMapIndex, texture: ref Texture2D) =
  setMaterialTexturePriv(material, mapType, texture[])
  GC_ref(texture)

But to be unloaded it must unref, however:

proc `=destroy`*(x: var Model) =
  for i in 0..<x.materialCount:
    for y in 0..<MaxMaterialMaps:
      if x.materials[i].maps[y].texture.id > 0:
        GC_unref(x.materials[i].maps[y].texture) # type mismatch
  unloadModel(x)

We lose the ref association...

planetis-m commented 1 year ago

One solution is to have global tables between textureId, meshId, shaderId and their count...

planetis-m commented 1 year ago

Idea, setMaterialTexture returns a MaterialTexture object that holds a reference to Model and Texture, on destroy they both get unref.

{.experimental: "views".}
type
  MaterialTexture* = object
    tex: ref Texture
    mat: lent MaterialMap # tracks the lifetime of model/materialmap whatever.

  var texture: ref Texture
  new(texture)
  texture[] = loadTextureFromImage(image) # Convert image to texture (VRAM)
  model.materials[0].maps[MaterialMapIndex.Diffuse].texture = texture[] # Set map diffuse texture
  let mattex = MaterialTexture(tex: texture, mat: model.materials[0].maps[MaterialMapIndex.Diffuse])

seems to work, but better left to be implemented by user code.

Nope doesn't work if you mutate model.

planetis-m commented 1 year ago

not worth it