public void CreateScene()
        {
            var canvas = Canvas.GetElementById(
                "game-window"
                );
            var engine = new Engine(
                canvas,
                true
                );
            var scene = new Scene(
                engine
                );
            var light0 = new PointLight(
                "Omni",
                new Vector3(
                    0,
                    2,
                    8
                    ),
                scene
                );
            var box1 = Mesh.CreateBox(
                "b1",
                1.0m,
                scene
                );
            var box2 = Mesh.CreateBox(
                "b1",
                1.0m,
                scene
                );

            box2.position = new Vector3(
                2m,
                0,
                0
                );
            var camera = new ArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(System.Math.PI / 2),
                (decimal)(System.Math.PI / 4),
                6,
                new Vector3(1, 0, 0),
                scene
                )
            {
                lowerRadiusLimit     = 2,
                upperRadiusLimit     = 10,
                wheelDeltaPercentage = 0.01m
            };

            scene.activeCamera = camera;
            camera.attachControl(
                canvas,
                false
                );
            engine.runRenderLoop(() => Task.Run(() => scene.render(true, false)));

            _engine = engine;
        }
        public void CreateScene()
        {
            var canvas = Canvas.GetElementById(
                "game-window"
                );
            var engine = new Engine(
                canvas,
                true
                );
            var scene = new Scene(
                engine
                );

            scene.clearColor = new Color4(0, 0, 0, 0);
            var light0 = new PointLight(
                "Omni",
                new Vector3(
                    0,
                    100,
                    8
                    ),
                scene
                );
            var light1 = new HemisphericLight(
                "HemisphericLight",
                new Vector3(
                    0,
                    100,
                    8
                    ),
                scene
                );
            var advancedTexture = AdvancedDynamicTexture.CreateFullscreenUI("UI");
            var UiPanel         = new StackPanel("name")
            {
                width               = "220px",
                fontSize            = "14px",
                horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_RIGHT,
                verticalAlignment   = Control.VERTICAL_ALIGNMENT_CENTER
            };

            advancedTexture.addControl(UiPanel);

            var house = SceneLoader.ImportMesh(
                null,
                "assets/",
                "Player.glb",
                scene,
                new Interop.Callbacks.ActionCallback <AbstractMesh[], IParticleSystem[], Skeleton[], AnimationGroup[], TransformNode[], Geometry[], Light[]>((arg1, arg2, arg3, arg4, arg5, arg6, arg7) =>
            {
                foreach (var animation in arg4)
                {
                    animation.stop();
                    _animationMap.Add(animation.name, animation);
                    AddRunAnimationButton(
                        UiPanel,
                        animation.name
                        );
                }
                if (_animationMap.Count > 0)
                {
                    _runningAnimation = _animationMap.First().Value;
                    _runningAnimation.start(true);
                }
                return(Task.CompletedTask);
            })
                );
            var camera = new ArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(System.Math.PI / 2),
                (decimal)(System.Math.PI / 4),
                3,
                new Vector3(0, 1, 0),
                scene
                )
            {
                lowerRadiusLimit     = 2,
                upperRadiusLimit     = 10,
                wheelDeltaPercentage = 0.01m
            };

            scene.activeCamera = camera;
            camera.attachControl(
                false
                );
            engine.runRenderLoop(new ActionCallback(
                                     () => Task.Run(() => scene.render(true, false))
                                     ));

            _engine = engine;
        }
        public async Task CreateSceneAsync()
        {
            var canvas = Canvas.GetElementById(
                "game-window"
                );
            var engine = new Engine(
                canvas,
                true
                );

            // This creates a basic Babylon Scene object (non-mesh)
            var scene = new Scene(engine);

            scene.clearColor = new Color4(
                0.31m,
                0.48m,
                0.64m,
                1
                );

            //add an arcRotateCamera to the scene
            var camera = new ArcRotateCamera(
                "camera",
                Tools.ToRadians(125),
                Tools.ToRadians(70), 25,
                new Vector3(0, 3, 0),
                scene
                );

            camera.lowerRadiusLimit = 10;
            camera.upperRadiusLimit = 40;

            // This attaches the camera to the canvas
            camera.attachControl(true);

            //array for holding the cannon and "paired" animation group
            var cannonAnimationPairings = new Dictionary <string, string>();

            //array for holding readyToPlay status for the cannons
            var cannonReadyToPlay = new Dictionary <string, int>();

            //Load the tower assets
            var pirateFortImportEntity = await SceneLoader.ImportMeshAsync(
                "",
                "https://models.babylonjs.com/pirateFort/",
                "pirateFort.glb",
                scene
                );

            var pirateFortImport = pirateFortImportEntity.ToEntity <SceneLoaderImportMeshEntity>();

            pirateFortImport.meshes[0].name = "pirateFort";
            scene.getMeshByName("sea").material.needDepthPrePass = true;
            scene.getLightByName("Sun").intensity = 12;

            //Load the cannon model and create clones
            var cannonImportResult = (await SceneLoader.ImportMeshAsync(
                                          "",
                                          "https://models.babylonjs.com/pirateFort/",
                                          "cannon.glb",
                                          scene
                                          )).ToEntity <SceneLoaderImportMeshEntity>();
            //remove the top level root node
            var cannon = cannonImportResult.meshes[0].getChildren()[0];

            cannon.setParent(null);
            cannonImportResult.meshes[0].dispose();

            //set the metadata of each mesh to filter on later
            var cannonMeshes = cannon.getChildMeshes();

            for (var i = 0; i < cannonMeshes.Length; i++)
            {
                var metadata = new NodeMetadata();
                metadata.name            = "cannon";
                cannonMeshes[i].metadata = metadata;
            }

            var importedAnimGroups = cannonImportResult.animationGroups;

            //loop through all imported animation groups and copy the animation curve data to an array.
            var animations = new Animation[importedAnimGroups.Length];

            for (var i = 0; i < importedAnimGroups.Length; i++)
            {
                importedAnimGroups[i].stop();
                animations[i] = importedAnimGroups[i].targetedAnimations[0].animation;
                importedAnimGroups[i].dispose();
            }

            //create a new animation group and add targeted animations based on copied curve data from the "animations" array.
            var cannonAnimGroup = new AnimationGroup(
                "cannonAnimGroup"
                );

            cannonAnimGroup.addTargetedAnimation(
                animations[0],
                cannon.getChildMeshes()[1]
                );
            cannonAnimGroup.addTargetedAnimation(
                animations[1],
                cannon.getChildMeshes()[0]
                );

            //create a box for particle emission, position it at the muzzle of the cannon, turn off visibility and parent it to the cannon mesh
            var particleEmitter = MeshBuilder.CreateBox(
                "particleEmitter",
                new { size = 0.05 },
                scene
                );

            particleEmitter.position = new Vector3(
                0,
                0.76m,
                1.05m
                );
            particleEmitter.rotation.x = Tools.ToRadians(78.5m);
            particleEmitter.isVisible  = false;
            particleEmitter.setParent(
                cannon.getChildMeshes()[1]
                );

            //load particle system from the snippet server and set the emitter to the particleEmitter. Set its stopDuration.
            var baseurl    = Tools.BaseUrl;
            var smokeBlast = await ParticleHelper.CreateFromSnippetAsync(
                "LCBQ5Y#6",
                scene,
                false,
                ParticleHelper.SnippetUrl
                );

            smokeBlast.emitter            = particleEmitter;
            smokeBlast.targetStopDuration = 0.2m;

            //load a cannon blast sound
            var cannonBlastSound = new Sound(
                "music",
                "https://assets.babylonjs.com/sound/cannonBlast.mp3",
                scene
                );

            //position and rotation data for the placement of the cannon clones
            var cannonPositionArray = new Vector3[][] {
                new Vector3[]
                {
                    new Vector3(0.97m, 5.52m, 1.79m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(0), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(1.08m, 2.32m, 3.05m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(0), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(1.46m, 2.35m, -0.73m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(90), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(1.45m, 5.52m, -1.66m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(90), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(1.49m, 8.69m, -0.35m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(90), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(-1.37m, 8.69m, -0.39m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(-90), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(0.58m, 4, -2.18m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(180), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(1.22m, 8.69m, -2.5m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(180), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(-1.31m, 2.33m, -2.45m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(180), Tools.ToRadians(180))
                },

                new Vector3[]
                {
                    new Vector3(-3.54m, 5.26m, -2.12m),
                    new Vector3(Tools.ToRadians(0), Tools.ToRadians(-90), Tools.ToRadians(180))
                }
            };

            //create 10 cannon clones, each with unique position/rotation data. Note that particle systems are cloned with parent meshes
            //also create 10 new animation groups with targeted animations applied to the newly cloned meshes
            for (var i = 0; i < 10; i++)
            {
                var cannonClone = cannon.clone <AbstractMesh>(
                    "cannonClone" + i
                    );
                cannonClone.position = cannonPositionArray[i][0];
                cannonClone.rotation = cannonPositionArray[i][1];
                var cannonAnimGroupClone = new AnimationGroup(
                    "cannonAnimGroupClone" + i
                    );
                cannonAnimGroupClone.addTargetedAnimation(
                    cannonAnimGroup.targetedAnimations[0].animation,
                    cannonClone.getChildMeshes()[1]);
                cannonAnimGroupClone.addTargetedAnimation(
                    cannonAnimGroup.targetedAnimations[1].animation,
                    cannonClone.getChildMeshes()[0]);

                //store a key/value pair of each clone name and the name of the associated animation group name.
                cannonAnimationPairings[cannonClone.name] = cannonAnimGroupClone.name;

                //store key/value pair for the cannon name and it's readyToPlay status as 1;
                cannonReadyToPlay[cannonClone.name] = 1;
            }
            //dispose of the original cannon, animation group, and particle system
            cannon.dispose();
            cannonAnimGroup.dispose();
            smokeBlast.dispose();

            //create an array for all particle systems in the scene, loop through it and stop all systems from playing.
            var smokeBlasts = scene.particleSystems;

            for (var i = 0; i < smokeBlasts.Length; i++)
            {
                smokeBlasts[i].stop();
            }

            //logic of what happens on a click
            scene.onPointerObservable.add((pointerInfo, eventState) =>
            {
                // PointerEventTypes.POINTERDOWN
                if (pointerInfo.type != 1)
                {
                    return(Task.CompletedTask);
                }
                var pickResult = pointerInfo.pickInfo;
                //check if a mesh was picked and if that mesh has specific metadata
                if (pickResult.pickedMesh != null &&
                    pickResult.pickedMesh.metadata != null)
                {
                    var metadataNode = pickResult.pickedMesh.metadata.ToEntity <NodeMetadata>();
                    if (metadataNode.name != "cannon")
                    {
                        return(Task.CompletedTask);
                    }
                    //find the top level parent (necessary since the cannon is an extra layer below the clone root)
                    var topParent = pickResult.pickedMesh.parent;
                    if (topParent.parent != null &&
                        topParent.parent.name != null)
                    {
                        topParent = topParent.parent;
                    }
                    //wrap all 'play' elements into a check to make sure the cannon can be played.
                    if (cannonReadyToPlay[topParent.name] == 1)
                    {
                        //set the readyToPlay status to 0
                        cannonReadyToPlay[topParent.name] = 0;
                        //loop through all of the animation groups in the scene and play the correct group based on the top level parent of the picked mesh.
                        var animationToPlay = cannonAnimationPairings[topParent.name];
                        for (var i = 0; i < scene.animationGroups.Length; i++)
                        {
                            if (scene.animationGroups[i].name == animationToPlay)
                            {
                                scene.animationGroups[i].play();
                                //after the animation has finished, set the readyToPlay status for this cannon to 1;
                                scene.animationGroups[i].onAnimationGroupEndObservable.addOnce((_, __) =>
                                {
                                    cannonReadyToPlay[topParent.name] = 1;

                                    return(Task.CompletedTask);
                                });
                            }
                        }
                        //loop through all particle systems in the scene, loop through all picked mesh submeshes. if there is a matching mesh and particle system emitter, start the particle system.
                        var childMeshes = pickResult.pickedMesh.getChildMeshes();
                        for (var i = 0; i < smokeBlasts.Length; i++)
                        {
                            for (var j = 0; j < childMeshes.Length; j++)
                            {
                                if (childMeshes[j].___guid == smokeBlasts[i].emitter.___guid)
                                {
                                    smokeBlasts[i].start();
                                }
                            }
                        }
                        cannonBlastSound.play();
                    }
                }

                return(Task.CompletedTask);
            });
            //scene.onPointerDown = function(evt, pickResult) {
            //    //check if a mesh was picked and if that mesh has specific metadata
            //    if (pickResult.pickedMesh && pickResult.pickedMesh.metadata === "cannon")
            //    {
            //        //find the top level parent (necessary since the cannon is an extra layer below the clone root)
            //        var topParent = pickResult.pickedMesh.parent;
            //        if (topParent.parent)
            //        {
            //            topParent = topParent.parent;
            //        }

            //        //wrap all 'play' elements into a check to make sure the cannon can be played.
            //        if (cannonReadyToPlay[topParent.name] === 1)
            //        {
            //            //set the readyToPlay status to 0
            //            cannonReadyToPlay[topParent.name] = 0;
            //            //loop through all of the animation groups in the scene and play the correct group based on the top level parent of the picked mesh.
            //            var animationToPlay = cannonAnimationPairings[topParent.name];
            //            for (var i = 0; i < scene.animationGroups.length; i++)
            //            {
            //                if (scene.animationGroups[i].name === animationToPlay)
            //                {
            //                    scene.animationGroups[i].play();
            //                    //after the animation has finished, set the readyToPlay status for this cannon to 1;
            //                    scene.animationGroups[i].onAnimationGroupEndObservable.addOnce(() =>
            //                    {
            //                        cannonReadyToPlay[topParent.name] = 1;
            //                    });
            //                }
            //            }
            //            //loop through all particle systems in the scene, loop through all picked mesh submeshes. if there is a matching mesh and particle system emitter, start the particle system.
            //            var childMeshes = pickResult.pickedMesh.getChildMeshes();
            //            for (var i = 0; i < smokeBlasts.length; i++)
            //            {
            //                for (var j = 0; j < childMeshes.length; j++)
            //                {
            //                    if (childMeshes[j] === smokeBlasts[i].emitter)
            //                    {
            //                        smokeBlasts[i].start();
            //                    }
            //                }
            //            }
            //            cannonBlastSound.play();
            //        }
            //    }
            //};

            _scene = scene;
            _scene.activeCamera = camera;
            engine.runRenderLoop(new ActionCallback(
                                     () => Task.Run(() => _scene.render(true, false))
                                     ));

            _engine = engine;
        }
Exemple #4
0
        public override Scene CreateScene(dom.HTMLCanvasElement canvas, Engine engine)
        {
            var scene = new Scene(engine);

            // Setup camera
            var camera = new ArcRotateCamera("Camera", 0, 0, 10, Vector3.Zero(), scene);

            camera.setPosition(new Vector3(-10, 10, 0));
            camera.attachControl(canvas, true);

            // Lights
            var light0 = new PointLight("Omni0", new Vector3(0, 10, 0), scene);
            var light1 = new PointLight("Omni1", new Vector3(0, -10, 0), scene);
            var light2 = new PointLight("Omni2", new Vector3(10, 0, 0), scene);
            var light3 = new DirectionalLight("Dir0", new Vector3(1, -1, 0), scene);

            var material = new StandardMaterial("kosh", scene);
            var sphere   = Mesh.CreateSphere("Sphere", 16, 3, scene);

            // Creating light sphere
            var lightSphere0 = Mesh.CreateSphere("Sphere0", 16, 0.5, scene);
            var lightSphere1 = Mesh.CreateSphere("Sphere1", 16, 0.5, scene);
            var lightSphere2 = Mesh.CreateSphere("Sphere2", 16, 0.5, scene);

            var redMaterial = new StandardMaterial("red", scene)
            {
                diffuseColor  = new Color3(0, 0, 0),
                specularColor = new Color3(0, 0, 0),
                emissiveColor = new Color3(1, 0, 0)
            };

            var greenMaterial = new StandardMaterial("green", scene)
            {
                diffuseColor  = new Color3(0, 0, 0),
                specularColor = new Color3(0, 0, 0),
                emissiveColor = new Color3(0, 1, 0)
            };

            var blueMaterial = new StandardMaterial("blue", scene)
            {
                diffuseColor  = new Color3(0, 0, 0),
                specularColor = new Color3(0, 0, 0),
                emissiveColor = new Color3(0, 0, 1)
            };

            lightSphere0.material = redMaterial;
            lightSphere1.material = greenMaterial;
            lightSphere2.material = blueMaterial;

            // Sphere material
            material.diffuseColor = new Color3(1, 1, 1);
            sphere.material       = material;

            // Lights colors
            light0.diffuse  = new Color3(1, 0, 0);
            light0.specular = new Color3(1, 0, 0);

            light1.diffuse  = new Color3(0, 1, 0);
            light1.specular = new Color3(0, 1, 0);

            light2.diffuse  = new Color3(0, 0, 1);
            light2.specular = new Color3(0, 0, 1);

            light3.diffuse  = new Color3(1, 1, 1);
            light3.specular = new Color3(1, 1, 1);

            // Animations
            var alpha = 0.0;

            scene.beforeRender = () => {
                light0.position = new Vector3(10 * es5.Math.sin(alpha), 0, 10 * es5.Math.cos(alpha));
                light1.position = new Vector3(10 * es5.Math.sin(alpha), 0, -10 * es5.Math.cos(alpha));
                light2.position = new Vector3(10 * es5.Math.cos(alpha), 0, 10 * es5.Math.sin(alpha));

                lightSphere0.position = light0.position;
                lightSphere1.position = light1.position;
                lightSphere2.position = light2.position;

                alpha += 0.01;
            };

            return(scene);
        }
Exemple #5
0
        public override Scene CreateScene(dom.HTMLCanvasElement canvas, Engine engine)
        {
            var scene = new Scene(engine);

            // Create camera and light
            var light  = new PointLight("Point", new Vector3(5, 10, 5), scene);
            var camera = new ArcRotateCamera("Camera", 1, 0.8, 8, new Vector3(0, 0, 0), scene);

            camera.attachControl(canvas, true);

            // Create a sprite manager to optimize GPU ressources
            // Parameters : name, imgUrl, capacity, cellSize, scene
            var spriteManagerTrees = new SpriteManager("treesManager", "https://demos.retyped.com/dist/babylon.js/img/palm.png", 2000, 800, scene);

            //We create 2000 trees at random positions
            for (var i = 0; i < 2000; i++)
            {
                var tree = new Sprite("tree", spriteManagerTrees);
                tree.position.x = es5.Math.random() * 100 - 50;
                tree.position.z = es5.Math.random() * 100 - 50;
                tree.isPickable = true;

                //Some "dead" trees
                if (es5.Math.round(es5.Math.random() * 5) == 0)
                {
                    tree.angle      = es5.Math.PI * 90 / 180;
                    tree.position.y = -0.3;
                }
            }

            //Create a manager for the player's sprite animation
            var spriteManagerPlayer = new SpriteManager("playerManager", "https://demos.retyped.com/dist/babylon.js/img/player.png", 2, 64, scene);

            // First animated player
            var player = new Sprite("player", spriteManagerPlayer);

            player.playAnimation(0, 40, true, 100, null);
            player.position.y = -0.3;
            player.size       = 0.3;
            player.isPickable = true;

            // Second standing player
            var player2 = new Sprite("player2", spriteManagerPlayer);

            player2.stopAnimation(); // Not animated
            player2.cellIndex  = 2;  // Going to frame number 2
            player2.position.y = -0.3;
            player2.position.x = 1;
            player2.size       = 0.3;
            player2.invertU    = -1; //Change orientation
            player2.isPickable = true;

            // Picking
            spriteManagerTrees.isPickable  = true;
            spriteManagerPlayer.isPickable = true;

            scene.onPointerDown = (evt, pickInfo) =>
            {
                var pickResult = (PickingInfo)scene.pickSprite(scene.pointerX, scene.pointerY);
                if (pickResult.hit)
                {
                    var sprite = (Sprite)pickResult.pickedSprite;
                    sprite.angle += 0.5;
                }
            };

            return(scene);
        }
Exemple #6
0
        public void CreateScene()
        {
            var canvas = Canvas.GetElementById(
                "game-window"
                );
            var engine = new Engine(
                canvas,
                true
                );
            var scene = new Scene(
                engine
                );
            var light1 = new HemisphericLight(
                "HemisphericLight",
                new Vector3(1, 1, 0),
                scene
                );

            var columns = 6m;
            var rows    = 1m;

            var faceUV = new Vector4[6];

            for (var i = 0; i < 6; i++)
            {
                faceUV[i] = new Vector4(
                    i / columns,
                    0,
                    (i + 1) / columns,
                    1m / rows
                    );
            }

            var mat = new StandardMaterial(
                "mat",
                scene
                );
            var texture = new Texture(
                scene,
                "https://assets.babylonjs.com/environments/numbers.jpg"
                );

            mat.diffuseTexture = texture;

            var alpha = 1;
            var red   = new Color4(
                1,
                0,
                0,
                alpha
                );
            var blue = new Color4(
                0,
                0,
                1,
                alpha
                );
            var green = new Color4(
                0,
                1,
                0,
                alpha
                );

            var options = new
            {
                faceUV,
                wrap       = true,
                width      = 1,
                height     = 2,
                depth      = 3,
                faceColors = new List <Color4> {
                    green, green, green, green, blue, red
                }
            };

            var box = MeshBuilder.CreateBox(
                "box",
                options,
                scene
                );

            box.material = mat;

            var camera = new ArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(Math.PI / 2),
                (decimal)(Math.PI / 4),
                10,
                new Vector3(0, 1, 0),
                scene
                );

            scene.activeCamera = camera;
            camera.attachControl(
                false
                );

            engine.runRenderLoop(new ActionCallback(
                                     () => Task.Run(() => scene.render(true, false))
                                     ));

            _engine = engine;
        }