koute/stdweb

Question: How to recreate a ReferenceType using only the numeric primitive?

hughlang opened this issue · 4 comments

Suppose you want to store the u32 value of a created stdweb object that wraps a Reference. For me, I am working with WebGLTexture objects. You can get the u32 value out like this

        let texture = try_opt(self.gl_ctx.create_texture(), "Create GL texture")?;
        let raw = texture.as_ref();
        let id = raw.as_raw() as u32;

Great! Now, I want to use the u32 value to recreate the WebGLTexture so I can bind it. I really don't know how and I've tried many things. Any ideas? I can get as far as this, and I get a Reference(u32) object but I can't get to the final step using downcast or any other means.

       let a_ref = Reference::from_raw_unchecked(img_id as i32);

Thanks for any help you can provide.

Pauan commented

Not sure why you're messing around with raw pointers (could you explain more?).

You also shouldn't be using hidden methods, since they're supposed to be internal.

But to answer your question, WebGLTexture doesn't exist in stdweb, how are you defining it?

Thanks for asking @Pauan. I am supporting both OpenGL and WebGL and the former lets you reference program, texture, location, etc through primitives like u32. With WebGL, I have to deal with opaque references that are hard to deconstruct and reconstruct. If I have a Trait or other system of passing around information, it is useful to have the most simple primitives. Of course, I can cache stuff and look it up, but it seems like the WebGL system is making it unnecessarily difficult for me.

WebGLTexture is getting generated as part of the gl-rs crate I think which uses stdweb to code-generate a ton of bindings. That's where this is coming from. It might not belong here, but this is just a starting point.

Pauan commented

Okay, so taking a look at the docs, it seems to have a TryFrom impl, so something like this should work:

use stdweb::unstable::TryInto;

let texture: WebGLTexture = a_ref.try_into().unwrap();

Thanks for the advice. It didn't work using your example, but it did give me a better understanding of the necessary imports. I didn't import ReferenceType before and I think that was one problem.

use stdweb::ReferenceType; // along with all the others

  let a_ref = Reference::from_raw_unchecked(img_id as i32);
  let result = WebGLTexture::from_reference_unchecked(a_ref);

Thanks so much. Closing this now.