IShadowCaster doesn't allow adding/removing shadow casters

I’m adding a mesh to an existing light’s shadow generator. But the returned object type (IShadowGenerator) doesn’t implement the addShadowCaster method. We can get around this by casting, but it feels like a hack… Maybe IShadowGenerator should have the addShadowCaster method?

// we have to upcast, because the method actually returns an IShadowGenerator,
// which doesn't implement `addShadowCaster`
let sg = light.getShadowGenerator() as ShadowGenerator | null
if (!sg)
  sg = new ShadowGenerator(1024, light)

sg.addShadowCaster(mesh)

I believe you need to call addShadowCaster from ShadowGenerator, not new ShadowCaster which doesn’t actually exist at all :slight_smile:

let sg = light.getShadowGenerator() as ShadowGenerator | null
   if (!sg)   {
   sg = new ShadowGenerator(1024, light)
   }
sg.addShadowCaster(mesh)

You’re absolutely right. We can simplify the code a bit:

const sg = light.getShadowGenerator() ?? new ShadowGenerator(1024, light)

Ah yes, typo. I updated the question.

That doesn’t work in TypeScript, because the types don’t match. The method returns an IShadowGenerator interface, not ShadowGenerator.

        const sg = light.getShadowGenerator() as ShadowGenerator ?? new ShadowGenerator(1024, light)
        sg.addShadowCaster(mesh)

Example - Babylon.js Playground

1 Like

@labris is right. I oversimplified it without testing :crazy_face:

You need to cast it.

I think @alekop wants to avoid typecasting.

I am wondering: the docs mention “addShadowCaster” in this context: Introduced with Babylon.js v3.1, there are two new helper functions to deal with shadow casters:

So maybe when they added the helpers they forgot to update the interface?


Oh, speaking of docs. This should work without typecasting:

shadowGenerator.getShadowMap().renderList.push(torus);

1 Like

Yes, this works - https://playground.babylonjs.com/#O9OMIN#2

        const sg = light.getShadowGenerator()?? new BABYLON.ShadowGenerator(1024, light)
        sg.getShadowMap().renderList.push(sphere);
2 Likes

All roads leads to Rome :smiley: