Beispiel #1
0
        private void GenerateBeforeAfterCollisionLogic(ICodeBlock codeBlock)
        {
            var beforeMethod = codeBlock.Function("public void", "RecordBeforeCollisionState");

            beforeMethod.Line("wasMovingForwardAtStartOfCollisionRecording = this.CurrentForwardSpeed > 0;");

            var afterMethod = codeBlock.Function("public void", "RecordAfterCollisionState");

            afterMethod.Line(@"
                bool isMovingForward = this.CurrentForwardSpeed > 0;
                if (this.CurrentForwardSpeed > 0)
                {
                    collisionHistory.LastTimeMovingForward = TimeManager.CurrentTime;
                }

                if (this.Brake.IsDown)
                {
                    collisionHistory.LastBrakePressedTime = TimeManager.CurrentTime;
                }

                if (wasMovingForwardAtStartOfCollisionRecording && !isMovingForward)
                {
                    // collided, moving in reverse
                    collisionHistory.LastReverseSendingCollisionTime = TimeManager.CurrentTime;
                }
");
        }
Beispiel #2
0
        private static void GenerateSetupCameraMethod(ICodeBlock classContents)
        {
            //internal static void SetupCamera(Camera cameraToSetUp, GraphicsDeviceManager graphicsDeviceManager)

            // for 360, which doesn't support optional parameters.
            ICodeBlock methodContents = classContents.Function(
                "internal static void",
                "SetupCamera",
                string.Format("Camera cameraToSetUp, GraphicsDeviceManager graphicsDeviceManager",
                              ProjectManager.GlueProjectSave.ResolutionWidth,
                              ProjectManager.GlueProjectSave.ResolutionHeight));

            methodContents.Line(string.Format("SetupCamera(cameraToSetUp, graphicsDeviceManager, {0}, {1});", ProjectManager.GlueProjectSave.ResolutionWidth,
                                              ProjectManager.GlueProjectSave.ResolutionHeight));



            methodContents = classContents.Function(
                "internal static void",
                "SetupCamera",
                "Camera cameraToSetUp, GraphicsDeviceManager graphicsDeviceManager, int width, int height");


            methodContents.TabCount = 3;

            AddSetResolutionCode(methodContents);

            AddUsePixelCoordinatesCode(methodContents);
        }
Beispiel #3
0
        private static ICodeBlock GetCreateNewFactoryMethod(ICodeBlock codeBlock, string className, bool poolObjects, string baseEntityName)
        {
            className = className.Substring(0, className.Length - "Factory".Length);

            // no tabs needed on first line
            codeBlock
            .Function(StringHelper.SpaceStrings("public", "static", className), "CreateNew", "float x = 0, float y = 0")
            .Line("return CreateNew(null, x, y);")
            .End();

            codeBlock = codeBlock
                        .Function(StringHelper.SpaceStrings("public", "static", className), "CreateNew", "Layer layer, float x = 0, float y = 0");

            codeBlock.Line(className + " instance = null;");

            if (poolObjects)
            {
                // only throw exception if pooled. This requires the user to pool the factory.
                // But do we want to have an explicit "IsInitialized" value? Maybe if this causes problems in the future...
                codeBlock.If("string.IsNullOrEmpty(mContentManagerName)")
                .Line("throw new System.Exception(\"You must first initialize the factory for this type because it is pooled. You can either add PositionedObjectList of type " +
                      className + " (the most common solution) or call Initialize in custom code\");")
                .End();
                codeBlock
                .Line("instance = mPool.GetNextAvailable();")
                .If("instance == null")
                .Line("mPool.AddToPool(new " + className + "(mContentManagerName, false));")
                .Line("instance =  mPool.GetNextAvailable();")
                .End()
                .Line("instance.AddToManagers(layer);");
            }
            else
            {
                // If not pooled don't require a content manager, can use the current screen's, so that init isn't required:

                //instance = new FactoryEntityWithNoList(mContentManagerName ?? FlatRedBall.Screens.ScreenManager.CurrentScreen.ContentManagerName, false);

                codeBlock
                .Line($"instance = new {className}(mContentManagerName ?? FlatRedBall.Screens.ScreenManager.CurrentScreen.ContentManagerName, false);")
                .Line("instance.AddToManagers(layer);");
            }

            codeBlock.Line("instance.X = x;");
            codeBlock.Line("instance.Y = y;");

            CreateAddToListCode(codeBlock, className);

            codeBlock = codeBlock
                        .If("EntitySpawned != null")
                        .Line("EntitySpawned(instance);")
                        .End()
                        .Line("return instance;")
                        .End();

            return(codeBlock);
        }
        private static ICodeBlock GetCreateNewFactoryMethod(ICodeBlock codeBlock, string className, bool poolObjects, string baseEntityName)
        {
            className = className.Substring(0, className.Length - "Factory".Length);

            // no tabs needed on first line
            codeBlock
            .Function(StringHelper.SpaceStrings("public", "static", className), "CreateNew", "")
            .Line("return CreateNew(null);")
            .End();

            codeBlock = codeBlock
                        .Function(StringHelper.SpaceStrings("public", "static", className), "CreateNew", "Layer layer")
                        .If("string.IsNullOrEmpty(mContentManagerName)")
                        .Line("throw new System.Exception(\"You must first initialize the factory to use it. You can either add PositionedObjectList of type " +
                              className + " (the most common solution) or call Initialize in custom code\");")
                        .End()

                        .Line(className + " instance = null;");

            if (poolObjects)
            {
                codeBlock
                .Line("instance = mPool.GetNextAvailable();")
                .If("instance == null")
                .Line("mPool.AddToPool(new " + className + "(mContentManagerName, false));")
                .Line("instance =  mPool.GetNextAvailable();")
                .End()
                .Line("instance.AddToManagers(layer);");
            }
            else
            {
                codeBlock
                .Line(string.Format("instance = new {0}(mContentManagerName, false);", className))
                .Line("instance.AddToManagers(layer);");
            }

            CreateAddToListIfNotNullCode(codeBlock, "mScreenListReference");

            if (!string.IsNullOrEmpty(baseEntityName))
            {
                CreateAddToListIfNotNullCode(codeBlock, "mBaseScreenListReference");
            }

            codeBlock = codeBlock
                        .If("EntitySpawned != null")
                        .Line("EntitySpawned(instance);")
                        .End()
                        .Line("return instance;")
                        .End();

            return(codeBlock);
        }
        private static ICodeBlock GeneratePreloadStateContentForStateType(ICodeBlock codeBlock, IElement element, List <StateSave> list, string variableType)
        {
            if (list.Count != 0)
            {
                codeBlock = codeBlock.Function("public static void", "PreloadStateContent", variableType + " state, string contentManagerName");
                codeBlock.Line("ContentManagerName = contentManagerName;");

                codeBlock = codeBlock.Switch("state");

                // Loop through states here and access properties that need the values
                foreach (StateSave state in list)
                {
                    codeBlock = codeBlock.Case(variableType + "." + state.Name);
                    foreach (InstructionSave instruction in state.InstructionSaves)
                    {
                        if (instruction.Value != null && instruction.Value is string)
                        {
                            // We insert a block so that object throwaway is not redefined in the switch scope.
                            // We do this instead of making an object throwaway above the switch so that we don't
                            // get warnings if is nothing to load
                            codeBlock.Block().Line("object throwaway = " + GetRightSideAssignmentValueAsString(element, instruction) + ";");
                        }
                    }
                    codeBlock = codeBlock.End();
                }

                codeBlock = codeBlock.End();

                codeBlock = codeBlock.End();
            }
            return(codeBlock);
        }
Beispiel #6
0
        private void GenerateHandleFileChanged(ICodeBlock codeBlock)
        {
            var method = codeBlock.Function("private static void", "HandleFileChanged", "object sender, System.IO.FileSystemEventArgs e");
            {
                var tryBlock = method.Try();

                tryBlock.Line("System.Threading.Thread.Sleep(500);");

                tryBlock.Line("var fullFileName = e.FullPath;");
                tryBlock.Line("var relativeFileName = FlatRedBall.IO.FileManager.MakeRelative(FlatRedBall.IO.FileManager.Standardize(fullFileName));");

                foreach (var rfs in GlueState.Self.CurrentGlueProject.GlobalFiles)
                {
                    bool shouldGenerate = rfs.LoadedAtRuntime && rfs.IsDatabaseForLocalizing == false;

                    if (shouldGenerate)
                    {
                        var fileName     = ProjectBase.AccessContentDirectory + rfs.Name.ToLower().Replace("\\", "/");
                        var instanceName = rfs.GetInstanceName();

                        var ifStatement = tryBlock.If($"relativeFileName == \"{fileName}\"");
                        {
                            ifStatement.Line($"Reload({instanceName});");
                        }
                    }
                }
                var catchBlock = tryBlock.End().Line("catch{}");
            }
        }
Beispiel #7
0
        private void GenerateInitializeLevel(ICodeBlock codeBlock, IElement element)
        {
            #region /////////////////////////////////Early out////////////////////////////////
            bool shouldGenerate = GetIfShouldGenerate(element);

            if (!shouldGenerate)
            {
                return;
            }

            ///////////////////////////////End early out/////////////////////////////
            #endregion


            codeBlock.Line("FlatRedBall.TileGraphics.LayeredTileMap CurrentTileMap;");
            var function = codeBlock.Function("void", "InitializeLevel", "string levelName");

            GenerateInitializeLevelObjects(function);

            GenerateInitializeCamera(function);

            GenerateAddCollisionAndEntities(function);

            //GenerateInitializeAnimations(function);
        }
Beispiel #8
0
        private static void GenerateResetCameraMethod(ICodeBlock classContents)
        {
            ICodeBlock methodContents = classContents.Function(
                "internal static void", "ResetCamera", "Camera cameraToReset");

            methodContents.Line("cameraToReset.X = 0;");
            methodContents.Line("cameraToReset.Y = 0;");

            methodContents.Line("cameraToReset.XVelocity = 0;");
            methodContents.Line("cameraToReset.YVelocity = 0;");

            // We can't detach because by this point the Camera may already
            // be attached to an Entity:
            //methodContents.Line("cameraToReset.Detach();");
            // November 6, 2015
            // I wondered why we
            // didn't do this until
            // I saw this comment. I'm
            // probably not going to be
            // the only one, so let's put
            // some info here:
            methodContents.Line("// Glue does not generate a detach call because the camera may be attached by this point");
            // I wondered "but why doesn't
            // the ResetCamera method get called
            // earlier, before the Camera has a chance
            // to attach itself to an entity. The reason
            // is because we can't do things to the camera
            // prior to AddToManagers because the camera may
            // be used in the previous screen if this screen is
            // loading async.
        }
Beispiel #9
0
 private void GenerateCallCustomInitialize(ElementSave elementSave, ICodeBlock currentBlock)
 {
     currentBlock = currentBlock.Function("private void", "CallCustomInitialize", "");
     {
         currentBlock.Line("CustomInitialize();");
     }
 }
        internal static ICodeBlock Function(this ICodeBlock codeBlock, string name, string parameters,
                                            bool Public            = false,
                                            bool Private           = false,
                                            bool Protected         = false,
                                            bool Internal          = false,
                                            bool ProtectedInternal = false,
                                            bool Static            = false,
                                            bool Override          = false,
                                            bool Virtual           = false,
                                            bool New    = false,
                                            string Type = null)
        {
            var modifiers =
                StringHelper.Modifiers(
                    Public: Public,
                    Private: Private,
                    Protected: Protected,
                    Internal: Internal,
                    ProtectedInternal: ProtectedInternal,
                    Static: Static,
                    Override: Override,
                    Virtual: Virtual,
                    Type: Type,
                    New: New
                    );

            return(codeBlock.Function(
                       modifiers
                       , name
                       , parameters
                       ));
        }
Beispiel #11
0
 private void GenerateAssignDefaultState(ElementSave elementSave, ICodeBlock currentBlock)
 {
     currentBlock = currentBlock.Function("public override void", "SetInitialState", "");
     {
         currentBlock.Line("this.CurrentVariableState = VariableState.Default;");
     }
 }
        private ICodeBlock GenerateInterpolateToStateAdvanced(ICodeBlock codeBlock, string enumName)
        {
            codeBlock = codeBlock.Function("public void", "InterpolateToState",
                                           enumName + " fromState, " + enumName + " toState, double secondsToTake, FlatRedBall.Glue.StateInterpolation.InterpolationType interpolationType, FlatRedBall.Glue.StateInterpolation.Easing easing");

            string variableName;

            if (enumName == "VariableState")
            {
                variableName = "CurrentState";
            }
            else
            {
                variableName = "Current" + enumName + "State";
            }

            codeBlock = codeBlock.If("secondsToTake <= 0");
            codeBlock.Line(variableName + " = toState;");
            codeBlock = codeBlock.End().Else();

            // Immediately set the state to the from state:
            codeBlock.Line(variableName + " = fromState;");

            codeBlock.Line("mFrom" + enumName + "Tween = fromState;");
            codeBlock.Line("mTo" + enumName + "Tween = toState;");

            codeBlock.Line(
                TweenerNameFor(enumName) + ".Start(0, 1, (float)secondsToTake, FlatRedBall.Glue.StateInterpolation.Tweener.GetInterpolationFunction(interpolationType, easing));");
            codeBlock = codeBlock.End();// else
            codeBlock = codeBlock.End();
            return(codeBlock);
        }
        private void GenerateHandleFileChanged(ICodeBlock codeBlock)
        {
            var method = codeBlock.Function("private static void", "HandleFileChanged", "object sender, System.IO.FileSystemEventArgs e");
            {
                var tryBlock = method.Try();

                tryBlock.Line("System.Threading.Thread.Sleep(500);");

                tryBlock.Line("var fullFileName = e.FullPath;");
                tryBlock.Line("var relativeFileName = FlatRedBall.IO.FileManager.MakeRelative(FlatRedBall.IO.FileManager.Standardize(fullFileName));");

                foreach(var rfs in GlueState.Self.CurrentGlueProject.GlobalFiles)
                {
                    bool shouldGenerate = rfs.LoadedAtRuntime && rfs.IsDatabaseForLocalizing == false;

                    if(shouldGenerate)
                    {
                        var fileName = ProjectBase.AccessContentDirectory + rfs.Name.ToLower().Replace("\\", "/");
                        var instanceName = rfs.GetInstanceName();

                        var ifStatement = tryBlock.If($"relativeFileName == \"{fileName}\"");
                        {
                            ifStatement.Line($"Reload({instanceName});");
                        }
                    }
                }
                var catchBlock = tryBlock.End().Line("catch{}");
            }
        }
        public override ICodeBlock GenerateAdditionalMethods(ICodeBlock codeBlock, IElement element)
        {
            EntitySave entitySave = element as EntitySave;

            if (entitySave == null || (!entitySave.ImplementsIClickable && !entitySave.ImplementsIWindow))
            {
                return codeBlock;
            }


            if (entitySave.ImplementsIWindow)
            {
                bool inheritsFromIWindow = entitySave.GetInheritsFromIWindow();

                // Add all the code that never changes if this is the base IWindow (doesn't have a parent IWindow)
                if (!inheritsFromIWindow)
                {
                    GenerateEnabledVariable(codeBlock, element);      
                }
            }

            IWindowCodeGenerator.WriteCodeForHasCursorOver(
                entitySave, codeBlock, entitySave.GetInheritsFromIWindowOrIClickable());

            var isVirtual = string.IsNullOrEmpty(entitySave.BaseEntity) || entitySave.GetInheritsFromIWindowOrIClickable() == false;

            codeBlock
                .Function("WasClickedThisFrame", "FlatRedBall.Gui.Cursor cursor", Public: true, Virtual: isVirtual, Override: !isVirtual, Type: "bool")
                .Line("return cursor.PrimaryClick && HasCursorOver(cursor);")
                .End();

            return codeBlock;
        }
        private void GenerateInitializeLevel(ICodeBlock codeBlock, IElement element)
        {
            #region /////////////////////////////////Early out////////////////////////////////
            bool shouldGenerate = GetIfShouldGenerate(element);

            if (!shouldGenerate)
            {
                return;
            }

            ///////////////////////////////End early out/////////////////////////////
            #endregion


            codeBlock.Line("FlatRedBall.TileGraphics.LayeredTileMap CurrentTileMap;");
            var function = codeBlock.Function("void", "InitializeLevel", "string levelName");

            GenerateInitializeLevelObjects(function);

            GenerateInitializeCamera(function);

            GenerateAddCollisionAndEntities(function);

            GenerateInitializeAnimations(function);
        }
Beispiel #16
0
 private void GenerateAddToManagersMethod(ElementSave elementSave, ICodeBlock currentBlock)
 {
     currentBlock = currentBlock.Function("public override void", "AddToManagers", "RenderingLibrary.SystemManagers managers, RenderingLibrary.Graphics.Layer layer");
     {
         currentBlock.Line("base.AddToManagers(managers, layer);");
     }
 }
Beispiel #17
0
        private static void GenerateHandleResize(ICodeBlock classContents)
        {
            var functionBlock = classContents.Function("private static void", "HandleResolutionChange", "object sender, System.EventArgs args");
            {
                functionBlock
                .If("Data.AspectRatio != null")
                .Line($"SetAspectRatioTo(Data.AspectRatio.Value, Data.DominantInternalCoordinates, Data.ResolutionWidth, Data.ResolutionHeight);");

                functionBlock.If("Data.Is2D && Data.ResizeBehavior == ResizeBehavior.IncreaseVisibleArea")
                .Line("FlatRedBall.Camera.Main.OrthogonalHeight = FlatRedBall.Camera.Main.DestinationRectangle.Height / (Data.Scale/ 100.0f);")
                .Line("FlatRedBall.Camera.Main.FixAspectRatioYConstant();");

                bool hasGumProject = GetIfHasGumProject();

                if (hasGumProject)
                {
                    var gumIfBlock = functionBlock.If("Data.ResizeBehaviorGum == ResizeBehavior.IncreaseVisibleArea");

                    gumIfBlock.Line("Gum.Wireframe.GraphicalUiElement.CanvasHeight = FlatRedBall.Camera.Main.DestinationRectangle.Height / (Data.Scale / 100.0f);");
                    gumIfBlock.Line("Gum.Wireframe.GraphicalUiElement.CanvasWidth = FlatRedBall.Camera.Main.DestinationRectangle.Width / (Data.Scale / 100.0f);");
                    gumIfBlock.Line("global::RenderingLibrary.SystemManagers.Default.Renderer.Camera.Zoom = Data.Scale/100.0f;");

                    var gumElseBlock = gumIfBlock.End().Else();

                    gumElseBlock.Line("var zoom = (Data.Scale / 100.0f) * FlatRedBall.Camera.Main.DestinationRectangle.Height / (float)Data.ResolutionHeight;");
                    gumElseBlock.Line("global::RenderingLibrary.SystemManagers.Default.Renderer.Camera.Zoom = zoom;");
                    gumElseBlock.Line("Gum.Wireframe.GraphicalUiElement.CanvasHeight = Data.ResolutionHeight;");
                    gumElseBlock.Line("Gum.Wireframe.GraphicalUiElement.CanvasWidth = Data.ResolutionWidth;");
                }
            }
        }
Beispiel #18
0
        private void GenerateInterpolateTo(ElementSave elementSave, ICodeBlock codeBlock, IEnumerable <StateSave> states, string enumName)
        {
            string qualifiedEnum = GueDerivingClassCodeGenerator.GueRuntimeNamespace + "." +
                                   FlatRedBall.IO.FileManager.RemovePath(elementSave.Name) + "Runtime." + enumName;

            // Make this thing return the Tweener so the uer can customize it
            string parameters = qualifiedEnum + " fromState," +
                                qualifiedEnum + " toState, double secondsToTake, " +
                                "FlatRedBall.Glue.StateInterpolation.InterpolationType interpolationType, FlatRedBall.Glue.StateInterpolation.Easing easing, object owner = null";

            codeBlock = codeBlock.Function("public FlatRedBall.Glue.StateInterpolation.Tweener", "InterpolateTo", parameters);
            {
                codeBlock.Line("FlatRedBall.Glue.StateInterpolation.Tweener tweener = new FlatRedBall.Glue.StateInterpolation.Tweener(from:0, to:1, duration:(float)secondsToTake, type:interpolationType, easing:easing );");
                codeBlock.If("owner == null")
                .Line("tweener.Owner = this;")
                .End()
                .Else()
                .Line("tweener.Owner = owner;");

                codeBlock.Line("tweener.PositionChanged = newPosition => this.InterpolateBetween(fromState, toState, newPosition);");
                codeBlock.Line("tweener.Start();");
                codeBlock.Line("StateInterpolationPlugin.TweenerManager.Self.Add(tweener);");
                codeBlock.Line("return tweener;");
            }
        }
        private void GenerateApplyStateOverride(ElementSave elementSave, ICodeBlock currentBlock)
        {
            currentBlock = currentBlock.Function("public override void", "ApplyState", "Gum.DataTypes.Variables.StateSave state");
            {
                currentBlock.Line("bool matches = this.ElementSave.AllStates.Contains(state);");

                var ifStatement = currentBlock.If("matches");
                {
                    ifStatement.Line("var category = this.ElementSave.Categories.FirstOrDefault(item => item.States.Contains(state));");

                    var innerIf = ifStatement.If("category == null");
                    {
                        foreach (var state in elementSave.States)
                        {
                            innerIf.Line($"if (state.Name == \"{state.Name}\") this.mCurrentVariableState = VariableState.{state.MemberNameInCode()};");
                        }
                    }
                    foreach (var category in elementSave.Categories)
                    {
                        var elseIf = ifStatement.ElseIf($"category.Name == \"{category.Name}\"");
                        {
                            foreach (var state in category.States)
                            {
                                elseIf.Line($"if(state.Name == \"{state.Name}\") this.mCurrent{category.Name}State = {category.Name}.{state.MemberNameInCode()};");
                            }
                        }
                    }
                }

                currentBlock.Line("base.ApplyState(state);");
            }
        }
        public override ICodeBlock GenerateAdditionalMethods(ICodeBlock codeBlock, IElement element)
        {
            EntitySave entitySave = element as EntitySave;

            if (entitySave == null || (!entitySave.ImplementsIClickable && !entitySave.ImplementsIWindow))
            {
                return(codeBlock);
            }


            if (entitySave.ImplementsIWindow)
            {
                bool inheritsFromIWindow = entitySave.GetInheritsFromIWindow();

                // Add all the code that never changes if this is the base IWindow (doesn't have a parent IWindow)
                if (!inheritsFromIWindow)
                {
                    GenerateEnabledVariable(codeBlock, element);
                }
            }

            IWindowCodeGenerator.WriteCodeForHasCursorOver(
                entitySave, codeBlock, entitySave.GetInheritsFromIWindowOrIClickable());

            var isVirtual = string.IsNullOrEmpty(entitySave.BaseEntity) || entitySave.GetInheritsFromIWindowOrIClickable() == false;

            codeBlock
            .Function("WasClickedThisFrame", "FlatRedBall.Gui.Cursor cursor", Public: true, Virtual: isVirtual, Override: !isVirtual, Type: "bool")
            .Line("return cursor.PrimaryClick && HasCursorOver(cursor);")
            .End();

            return(codeBlock);
        }
Beispiel #21
0
        private static string GenerateEmptyCustomEntityNetworkCode(EntitySave entitySave)
        {
            ICodeBlock topBlock = new CodeBlockBaseNoIndent(null);

            string entityNamespace = CodeGeneratorCommonLogic.GetElementNamespace(entitySave);

            ICodeBlock codeBlock = topBlock.Namespace(entityNamespace);

            codeBlock = codeBlock.Class("public partial", entitySave.GetStrippedName());

            codeBlock.Function("void", "CustomUpdateFromState", $"{CodeGeneratorCommonLogic.GetNetStateFullName(entitySave)} state");
            codeBlock.Function("void", "CustomGetState", $"{CodeGeneratorCommonLogic.GetNetStateFullName(entitySave)} state");



            return(topBlock.ToString());
        }
Beispiel #22
0
        private static void GenerateGeneratedInitialize(ICodeBlock codeBlock)
        {
            var method = codeBlock.Function("partial void", "GeneratedInitialize", null);

            foreach (var generator in Generators)
            {
                generator.GenerateInitialize(method);
            }
        }
Beispiel #23
0
        private static void GenerateGeneratedDraw(ICodeBlock codeBlock)
        {
            var method = codeBlock.Function("partial void", "GeneratedDraw", "Microsoft.Xna.Framework.GameTime gameTime");

            foreach (var generator in Generators)
            {
                generator.GenerateDraw(method);
            }
        }
Beispiel #24
0
        private void GenerateInterpolateToFromCurrent(ICodeBlock currentBlock, string enumType, bool isRelative)
        {
            string functionName = "InterpolateTo";

            string whereToLook = "States";

            if (enumType != "VariableState")
            {
                whereToLook = $"Categories.First(item => item.Name == \"{enumType}\").States";
            }


            string toStateRightSide = $"this.ElementSave.{whereToLook}.First(item => item.Name == toState.ToString());";

            if (isRelative)
            {
                functionName = "InterpolateToRelative";

                toStateRightSide = "AddToCurrentValuesWithState(toState);";
            }

            currentBlock = currentBlock.Function("public FlatRedBall.Glue.StateInterpolation.Tweener", functionName,
                                                 enumType + " toState, double secondsToTake, FlatRedBall.Glue.StateInterpolation.InterpolationType interpolationType, FlatRedBall.Glue.StateInterpolation.Easing easing, object owner = null ");



            currentBlock.Line("Gum.DataTypes.Variables.StateSave current = GetCurrentValuesOnState(toState);");

            currentBlock.Line("Gum.DataTypes.Variables.StateSave toAsStateSave = " + toStateRightSide);

            currentBlock.Line("FlatRedBall.Glue.StateInterpolation.Tweener tweener = new FlatRedBall.Glue.StateInterpolation.Tweener(from: 0, to: 1, duration: (float)secondsToTake, type: interpolationType, easing: easing);");
            currentBlock.If("owner == null")
            .Line("tweener.Owner = this;")
            .End()
            .Else()
            .Line("tweener.Owner = owner;");

            currentBlock.Line("tweener.PositionChanged = newPosition => this.InterpolateBetween(current, toAsStateSave, newPosition);");

            string variableName;

            if (enumType == "VariableState")
            {
                variableName = "CurrentVariableState";
            }
            else
            {
                variableName = $"Current{enumType}State";
            }

            currentBlock.Line($"tweener.Ended += ()=> this.{variableName} = toState;");
            currentBlock.Line("tweener.Start();");

            currentBlock.Line("StateInterpolationPlugin.TweenerManager.Self.Add(tweener);");
            currentBlock.Line("return tweener;");
        }
Beispiel #25
0
        private void GenerateCreateChildrenRecursively(ElementSave elementSave, ICodeBlock currentBlock)
        {
            currentBlock = currentBlock.Function("public override void", "CreateChildrenRecursively", "Gum.DataTypes.ElementSave elementSave, RenderingLibrary.SystemManagers systemManagers");
            {
                currentBlock.Line("base.CreateChildrenRecursively(elementSave, systemManagers);");
                currentBlock.Line("this.AssignReferences();");
            }

            //public virtual void CreateChildrenRecursively(ElementSave elementSave, SystemManagers systemManagers)
        }
        private static void GenerateRequestDestroy(ICodeBlock codeBlock)
        {
            var requestDestroyMethod = codeBlock.Function(
                "public void", "RequestDestroyEntity", "RedGrin.INetworkEntity entity");

            requestDestroyMethod.Line(
                "(entity as FlatRedBall.Graphics.IDestroyable).Destroy();");
            requestDestroyMethod.Line(
                "CustomRequestDestroyNetworkEntity(entity);");
        }
        public static ICodeBlock Constructor(this ICodeBlock codeBlock, string pre, string name, string parameters, string baseOrThisCall = null)
        {
            var toReturn = codeBlock.Function(pre, name, parameters);

            if (!string.IsNullOrEmpty(baseOrThisCall))
            {
                // Insert at index 1, after the function header, but before the opening {
                toReturn.PreCodeLines.Insert(1, new CodeLine("\t: " + baseOrThisCall));
            }

            return(toReturn);
        }
Beispiel #28
0
        private void GenerateLateralSpeedAdjustmentActivityMethod(ICodeBlock codeBlock)
        {
            codeBlock = codeBlock.Function("private void", "LateralSpeedAdjustmentActivity", "");

            codeBlock.Line(@"
            float lateralSpeed = CurrentLateralSpeed;

            if (lateralSpeed != 0)
            {
                var velocity2D = Velocity;
                velocity2D.Z = 0;

                float lateralDampening = EffectiveStability; // this makes the car not slide
                float forwardPercentage = CurrentForwardSpeed / velocity2D.Length();

                float amountToAdjustBy = lateralDampening * TimeManager.SecondDifference;
                if (amountToAdjustBy > Math.Abs(lateralSpeed))
                {
                    amountToAdjustBy = Math.Abs(lateralSpeed);
                }

                lateralToForwardTransferRatio = forwardPercentage;

                var whatToSubtract = amountToAdjustBy * Right * Math.Sign(lateralSpeed);

                float lengthSquaredBeforeSubtraction = velocity2D.LengthSquared();

                if (lengthSquaredBeforeSubtraction != 0)
                {
                    Velocity -= whatToSubtract;

                    float optimalForwardVectorLength = (float)System.Math.Sqrt(
                        lengthSquaredBeforeSubtraction - (CurrentLateralSpeed * CurrentLateralSpeed));
                    float currentForwardVectorLength = CurrentForwardSpeed;
                    if (CurrentForwardSpeed > 0)
                    {
                        float optimalAdd = optimalForwardVectorLength - currentForwardVectorLength;

                        float actualAdd = optimalAdd * forwardPercentage;

                        this.Velocity += actualAdd * Forward;
                    }
                }
            }
");


            /*
             *
             *
             */
        }
Beispiel #29
0
 private void GenerateRaiseExposedEvents(ElementSave elementSave, ICodeBlock currentBlock)
 {
     foreach (var eventSave in elementSave.Events.Where(item => !string.IsNullOrEmpty(item.ExposedAsName)))
     {
         var function = currentBlock.Function("void", "Raise" + eventSave.ExposedAsName, "FlatRedBall.Gui.IWindow callingWindow");
         {
             var ifBlock = function.If(eventSave.ExposedAsName + " != null");
             {
                 ifBlock.Line(eventSave.ExposedAsName + "(this);");
             }
         }
     }
 }
        private static void GenerateHandleResize(ICodeBlock classContents)
        {
            var functionBlock = classContents.Function("private static void", "HandleResolutionChange", "object sender, System.EventArgs args");
            {
                functionBlock
                .If("Data.AspectRatio != null")
                .Line($"SetAspectRatioTo(Data.AspectRatio.Value, Data.DominantInternalCoordinates, Data.ResolutionWidth, Data.ResolutionHeight);");

                functionBlock.If("Data.Is2D && Data.ResizeBehavior == ResizeBehavior.IncreaseVisibleArea")
                .Line("FlatRedBall.Camera.Main.OrthogonalHeight = FlatRedBall.Camera.Main.DestinationRectangle.Height / (Data.Scale/ 100.0f);")
                .Line("FlatRedBall.Camera.Main.FixAspectRatioYConstant();");
            }
        }
Beispiel #31
0
        private void GenerateAddToManagersMethod(ElementSave elementSave, ICodeBlock currentBlock)
        {
            currentBlock = currentBlock.Function("public override void", "AddToManagers", "RenderingLibrary.SystemManagers managers, RenderingLibrary.Graphics.Layer layer");
            {
                // Used to generate FRB behavior code addition here, but instances which are children of
                // other instances don't have their AddToManagers called.
                // Moving it to assign references
                //GenerateStandardFrbBehaviorCode(elementSave, currentBlock);


                currentBlock.Line("base.AddToManagers(managers, layer);");
            }
        }
Beispiel #32
0
        private void GenerateAssignDefaultState(ElementSave elementSave, ICodeBlock currentBlock)
        {
            currentBlock = currentBlock.Function("public override void", "SetInitialState", "");
            {
                bool shouldCallBase = elementSave is StandardElementSave == false;
                if (shouldCallBase)
                {
                    currentBlock.Line("base.SetInitialState();");
                }
                currentBlock.Line("this.CurrentVariableState = VariableState.Default;");

                currentBlock.Line("CallCustomInitialize();");
            }
        }
        private static ICodeBlock GetDestroyFactoryMethod(ICodeBlock codeBlock, string className)
        {
            className = className.Substring(0, className.Length - "Factory".Length);

            codeBlock
            .Function("public static void", "Destroy", "")
            .Line("mContentManagerName = null;")
            .Line("mScreenListReference = null;")
            .Line("mPool.Clear();")
            .Line("EntitySpawned = null;")
            .End();

            return(codeBlock);
        }
        private void GenerateInterpolateBetween(ElementSave elementSave, ICodeBlock currentBlock,
            string enumType, IEnumerable<StateSave> states)
        {
            // We used to only generate these if there was were any states in this category, but
            // since Gum generated code supports dynamic states, there could be states in a category
            // even if they're not defined in Gum.
            //if (states.Count() > 0)
            {
                currentBlock = currentBlock.Function("public void",
                    "InterpolateBetween", enumType + " firstState, " + enumType + " secondState, float interpolationValue");

                GenerateDebugCheckForInterpolationValueNaN(currentBlock);

                Dictionary<VariableSave, InterpolationCharacteristic> interpolationCharacteristics =
                   new Dictionary<VariableSave, InterpolationCharacteristic>();

                CreateStartingValueVariables(elementSave, states, currentBlock, interpolationCharacteristics);

                currentBlock = currentBlock.Switch("firstState");
                currentBlock = SetInterpolateBetweenValuesForStates(elementSave, enumType, states, currentBlock,
                    interpolationCharacteristics, FirstValue);
                currentBlock = currentBlock.End();

                currentBlock = currentBlock.Switch("secondState");
                currentBlock = SetInterpolateBetweenValuesForStates(elementSave, enumType, states, currentBlock,
                    interpolationCharacteristics, SecondValue);
                currentBlock = currentBlock.End();


                currentBlock = AssignValuesUsingStartingValues(elementSave, currentBlock, interpolationCharacteristics);

                currentBlock = currentBlock.If("interpolationValue < 1");

                string fieldToAssign;
                if (enumType == "VariableState")
                {
                    fieldToAssign = "mCurrentVariableState";
                }
                else
                {
                    fieldToAssign = "mCurrent" + enumType + "State";
                }

                currentBlock.Line(fieldToAssign + " = firstState;");
                currentBlock = currentBlock.End().Else();
                currentBlock.Line(fieldToAssign + " = secondState;");
                currentBlock = currentBlock.End();
            }
        }
        private void GenerateAnimateForCategory(ICodeBlock currentBlock, string categoryName, List<Gum.DataTypes.Variables.StateSave> states)
        {
            string propertyToAssign;
            if (categoryName == "VariableState")
            {
                propertyToAssign = "this.CurrentVariableState";
            }
            else
            {
                propertyToAssign = "this.Current" + categoryName + "State";
            }
            currentBlock = currentBlock.Function("public void", "Animate",
                "System.Collections.Generic.IEnumerable<FlatRedBall.Gum.Keyframe<" + categoryName + ">> keyframes");
            {
                currentBlock.Line("bool isFirst = true;");
                currentBlock.Line("FlatRedBall.Gum.Keyframe<" + categoryName + "> lastKeyframe = null;");

                var foreachBlock = currentBlock.ForEach("var frame in keyframes");
                {
                    var ifBlock = foreachBlock.If("isFirst");
                    {
                        ifBlock.Line("isFirst = false;");
                        ifBlock.Line(propertyToAssign + " = frame.State;");

                    }
                    var elseBlock = ifBlock.End().Else();
                    {
                        elseBlock.Line("float timeToTake = frame.Time - lastKeyframe.Time;");
                        elseBlock.Line("var fromState = lastKeyframe.State;");
                        elseBlock.Line("var toState = frame.State;");
                        elseBlock.Line("var interpolationType = lastKeyframe.InterpolationType;");
                        elseBlock.Line("var easing = lastKeyframe.Easing;");

                        elseBlock.Line(
                            "System.Action action = () => this.InterpolateTo(fromState, toState, timeToTake, interpolationType, easing, {});");

                        elseBlock.Line(
                            "FlatRedBall.Instructions.DelegateInstruction instruction = new FlatRedBall.Instructions.DelegateInstruction(action);");
                        elseBlock.Line("instruction.Target = this;");
                        elseBlock.Line("instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + lastKeyframe.Time;");

                        elseBlock.Line("FlatRedBall.Instructions.InstructionManager.Instructions.Add(instruction);");
                    }

                    foreachBlock.Line("lastKeyframe = frame;");
                }
            }
        }
 private static void GenerateInitialize(ICodeBlock codeBlock)
 {
     var initializeMethod = codeBlock.Function("private static void", "InitializeFileWatch", "");
     {
         initializeMethod.Line("string globalContent = FlatRedBall.IO.FileManager.RelativeDirectory + \"content/globalcontent/\";");
         var ifBlock = initializeMethod.If("System.IO.Directory.Exists(globalContent)");
         {
             ifBlock.Line("watcher = new System.IO.FileSystemWatcher();");
             ifBlock.Line("watcher.Path = globalContent;");
             ifBlock.Line("watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;");
             ifBlock.Line("watcher.Filter = \"*.*\";");
             ifBlock.Line("watcher.Changed += HandleFileChanged;");
             ifBlock.Line("watcher.EnableRaisingEvents = true;");
         }
     }
 }
        public override ICodeBlock GenerateAdditionalMethods(ICodeBlock codeBlock, FlatRedBall.Glue.SaveClasses.IElement element)
        {
            //////////////////////////EARLY OUT//////////////////////////////////////
            if (element is ScreenSave)
            {
                return codeBlock;
            }
            ///////////////////////END EARLY OUT/////////////////////////////////////

            codeBlock = codeBlock.Function("public void", "MoveToLayer", "Layer layerToMoveTo");

            foreach (NamedObjectSave nos in element.NamedObjects)
            {
                if (!nos.IsDisabled)
                {
                    if (nos.GetAssetTypeInfo() != null && !string.IsNullOrEmpty(nos.GetAssetTypeInfo().RemoveFromLayerMethod))
                    {
                        NamedObjectSaveCodeGenerator.AddIfConditionalSymbolIfNecesssary(codeBlock, nos);
                        bool shouldSkip = GetShouldSkip(nos);

                        if (!shouldSkip)
                        {
                            codeBlock.If("LayerProvidedByContainer != null")
                                .Line(nos.GetAssetTypeInfo().RemoveFromLayerMethod.Replace("this", nos.InstanceName).Replace("mLayer", "LayerProvidedByContainer") + ";")
                            .End();

                            codeBlock.Line(nos.GetAssetTypeInfo().LayeredAddToManagersMethod[0].Replace("this", nos.InstanceName).Replace("mLayer", "layerToMoveTo") + ";");
                        }
                        NamedObjectSaveCodeGenerator.AddEndIfIfNecessary(codeBlock, nos);
                    }
                    else if (nos.SourceType == SourceType.Entity && !string.IsNullOrEmpty(nos.SourceClassType))
                    {
                        NamedObjectSaveCodeGenerator.AddIfConditionalSymbolIfNecesssary(codeBlock, nos);
                        codeBlock.Line(nos.InstanceName + ".MoveToLayer(layerToMoveTo);");
                        NamedObjectSaveCodeGenerator.AddEndIfIfNecessary(codeBlock, nos);
                    }
                }
            }

            codeBlock.Line("LayerProvidedByContainer = layerToMoveTo;");

            codeBlock = codeBlock.End();

            return codeBlock;
        }
        private static ICodeBlock GetDestroyFactoryMethod(ICodeBlock codeBlock, string className)
        {
            className = className.Substring(0, className.Length - "Factory".Length);

            codeBlock
                .Function("public static void", "Destroy", "")
                    .Line("mContentManagerName = null;")
                    .Line("mScreenListReference = null;")
                    .Line("mPool.Clear();")
                    .Line("EntitySpawned = null;")
                .End();

            return codeBlock;
        }
Beispiel #39
0
        private static void GenerateAssignCustomVariables(ICodeBlock codeBlock, IElement element)
        {
            bool inherits = !string.IsNullOrEmpty(element.BaseElement) && !element.InheritsFromFrbType();

            
            if (inherits)
            {
                codeBlock = codeBlock.Function("public override void", "AssignCustomVariables", "bool callOnContainedElements");
                codeBlock.Line("base.AssignCustomVariables(callOnContainedElements);");
            }
            else
            {
                codeBlock = codeBlock.Function("public virtual void", "AssignCustomVariables", "bool callOnContainedElements");
            }

            // call AssignCustomVariables on all contained objects before assigning custom variables on "this"
            var ifCallOnContainedElements = codeBlock.If("callOnContainedElements");

            var listOfItems = element.NamedObjects.Where(item=>
                item.IsFullyDefined &&
                !item.IsDisabled &&
                item.Instantiate &&
                !item.SetByContainer &&
                !item.SetByDerived
                ).ToList();


            GenerateAssignmentForListOfObjects(codeBlock, element, ifCallOnContainedElements, listOfItems);

            


            foreach (CustomVariable customVariable in element.CustomVariables)
            {
                CustomVariableCodeGenerator.AppendAssignmentForCustomVariableInElement(codeBlock, customVariable, element);
            }

            EventCodeGenerator.GenerateAddToManagersBottomUp(codeBlock, element);
        }
        private static void GenerateResetCameraMethod(ICodeBlock classContents)
        {
            ICodeBlock methodContents = classContents.Function(
                "internal static void", "ResetCamera", "Camera cameraToReset");

            methodContents.Line("cameraToReset.X = 0;");
            methodContents.Line("cameraToReset.Y = 0;");

            methodContents.Line("cameraToReset.XVelocity = 0;");
            methodContents.Line("cameraToReset.YVelocity = 0;");

            // We can't detach because by this point the Camera may already
            // be attached to an Entity:
            //methodContents.Line("cameraToReset.Detach();");
            // November 6, 2015
            // I wondered why we
            // didn't do this until
            // I saw this comment. I'm
            // probably not going to be 
            // the only one, so let's put
            // some info here:
            methodContents.Line("// Glue does not generate a detach call because the camera may be attached by this point");
            // I wondered "but why doesn't
            // the ResetCamera method get called
            // earlier, before the Camera has a chance
            // to attach itself to an entity. The reason
            // is because we can't do things to the camera
            // prior to AddToManagers because the camera may
            // be used in the previous screen if this screen is
            // loading async. 


        }
        private static ICodeBlock GeneratePreloadStateContentForStateType(ICodeBlock codeBlock, IElement element, List<StateSave> list, string variableType)
        {
            if (list.Count != 0)
            {

                codeBlock = codeBlock.Function("public static void", "PreloadStateContent", variableType + " state, string contentManagerName");
                codeBlock.Line("ContentManagerName = contentManagerName;");

                codeBlock = codeBlock.Switch("state");

                // Loop through states here and access properties that need the values
                foreach (StateSave state in list)
                {
                    codeBlock = codeBlock.Case(variableType + "." + state.Name);
                    foreach (InstructionSave instruction in state.InstructionSaves)
                    {
                        if (instruction.Value != null && instruction.Value is string)
                        {
                            // We insert a block so that object throwaway is not redefined in the switch scope.
                            // We do this instead of making an object throwaway above the switch so that we don't
                            // get warnings if is nothing to load
                            codeBlock.Block().Line("object throwaway = " + GetRightSideAssignmentValueAsString(element, instruction) + ";");
                        }
                    }
                    codeBlock = codeBlock.End();

                }

                codeBlock = codeBlock.End();

                codeBlock = codeBlock.End();
            }
            return codeBlock;
        }
        public static ICodeBlock FillWithGeneratedEventCode(ICodeBlock currentBlock, EventResponseSave ers, IElement element)
        {
            EventSave eventSave = ers.GetEventSave();

            string args = ers.GetArgsForMethod(element);

            if (!string.IsNullOrEmpty(ers.SourceObject) && !string.IsNullOrEmpty(ers.SourceObjectEvent))
            {
                currentBlock = currentBlock
                    .Function("void", "On" + ers.EventName + "Tunnel", args);

                string reducedArgs = StripTypesFromArguments(args);

                currentBlock.If("this." + ers.EventName + " != null")
                    .Line(ers.EventName + "(" + reducedArgs + ");")
                    .End();

                currentBlock = currentBlock.End();
            }
            return currentBlock;
        }
        public static ICodeBlock FillWithCustomEventCode(ICodeBlock currentBlock, EventResponseSave ers, string contents, IElement element)
        {
            string args = ers.GetArgsForMethod(element);

            // We used to not 
            // generate the empty
            // shell of an event if
            // the contents were empty.
            // However now we want to for
            // two reasons:
            // 1:  A user may want to add an
            // event in Glue, but then mdoify
            // the event in Visual Studio.  The
            // user shouldn't be forced into adding
            // some content in Glue first to wdit the
            // event in Visual Studio.
            // 2:  A designer may decide to remove the 
            // contents of a method.  If this happens then
            // code that the designer doesn't work with shouldn't
            // break (IE, if the code calls the OnXXXX method).
            //if (!string.IsNullOrEmpty(contents))
            {

                // Need to modify the event CSV to include the arguments for this event

                currentBlock = currentBlock
                    .Function("void", "On" + ers.EventName, args);

                currentBlock.TabCharacter = "";

                int tabCount = currentBlock.TabCount;
                currentBlock.TabCount = 0;

                currentBlock
                        .Line(contents);

                currentBlock = currentBlock.End();
            }
            return currentBlock;
        }
        private static void GenerateGetMember(ICodeBlock codeBlock, SaveClasses.IElement element)
        {
            #region GetMember (Instance members)

            // GlobalContent is a static class, so it can't have a non-static GetMember method
            // Update June 25, 2011:  This has been moved
            // to a code generator which only works on Elements
            // so we know we're not global content
            //if (!isGlobalContent)
            //{

            var func = codeBlock.Function("object", "GetMember", "string memberName");
            ICodeBlock switchBlock = null;

            bool hasPrependedSwitch = false;

            foreach (ReferencedFileSave rfs in element.ReferencedFiles)
            {
                // Localization databases currently don't create members
                if (rfs.LoadedAtRuntime && !rfs.IsDatabaseForLocalizing &&
                    (rfs.GetAssetTypeInfo() == null || !string.IsNullOrEmpty( rfs.GetAssetTypeInfo().QualifiedRuntimeTypeName.QualifiedType))
                    
                    )
                {

                    if (!hasPrependedSwitch)
                    {
                        // We do the switch here 
                        // so that if there are no
                        // RFS's that the user can get,
                        // we don't want to generate a switch.
                        // This eliminates warnings.
                        hasPrependedSwitch = true;

                        switchBlock = func.Switch("memberName");
                    }

                    AddIfConditionalSymbolIfNecesssary(switchBlock, rfs);
                    string instanceName = rfs.GetInstanceName();

                    switchBlock.CaseNoBreak("\"" + instanceName + "\"")
                               .Line("return " + instanceName + ";");
                    AddEndIfIfNecessary(switchBlock, rfs);
                }
                //stringBuilder.AppendLine("\t\t\t\t\tbreak;");
            }

            func.Line("return null;");
            #endregion

        }
        public override ICodeBlock GenerateAdditionalMethods(ICodeBlock codeBlock, IElement element)
        {
            if(IsLoadingScreen(element))
            {
                codeBlock
                    .Line("static string mNextScreenToLoad;")
                    .Property("public static string", "NextScreenToLoad")
                        .Get()
                            .Line("return mNextScreenToLoad;")
                        .End()
                        .Set()
                            .Line("mNextScreenToLoad = value;")
                        .End()
                    .End();


                string screenName =
                    FileManager.RemovePath(element.Name);

                
                
                codeBlock
                    .Function("public static void", "TransitionToScreen", "System.Type screenType, System.Action<FlatRedBall.Screens.Screen> screenCreatedCallback = null")
                        .Line("TransitionToScreen(screenType.FullName, screenCreatedCallback);")
                    .End();


                codeBlock
                    .Function("public static void", "TransitionToScreen", "string screenName, System.Action<FlatRedBall.Screens.Screen> screenCreatedCallback = null")
                        .Line("Screen currentScreen = ScreenManager.CurrentScreen;")
                        .Line("currentScreen.IsActivityFinished = true;")
                        .Line("currentScreen.NextScreen = typeof(" + screenName + ").FullName;")
                        .Line("mNextScreenToLoad = screenName;")
                        .Line("nextCallback = screenCreatedCallback;")
                    .End();


                codeBlock
                    .Function("void", "AsyncActivity", "")
                        .Switch("AsyncLoadingState")
                            .Case("FlatRedBall.Screens.AsyncLoadingState.NotStarted")
                                .If("!string.IsNullOrEmpty(mNextScreenToLoad)")
                                    .Line("#if REQUIRES_PRIMARY_THREAD_LOADING")
                                    .If("HasDrawBeenCalled")
                                        .Line("MoveToScreen(mNextScreenToLoad);")
                                    .End()
                                    .Line("#else")
                                    .Line("StartAsyncLoad(mNextScreenToLoad);")
                                    .Line("#endif")
                                .End()
                            .End()
                            .Case("FlatRedBall.Screens.AsyncLoadingState.LoadingScreen")
                            .End()
                            .Case("FlatRedBall.Screens.AsyncLoadingState.Done")
                    // The loading screen can be used to rehydrate.  
                                .Line("FlatRedBall.Screens.ScreenManager.ShouldActivateScreen = false;")
                                
                                .Line("FlatRedBall.Screens.ScreenManager.MoveToScreen(mNextScreenToLoad, nextCallback);")
                            .End()
                        .End()
                    .End();
            }

            return codeBlock;
        }
        private void GenerateStopAnimations(ElementSave elementSave, ICodeBlock currentBlock)
        {
            bool hasBase = !string.IsNullOrEmpty(elementSave.BaseType);

            if(hasBase)
            {
                var elementBase = Gum.Managers.ObjectFinder.Self.GetElementSave(elementSave.BaseType);

                if(elementBase is StandardElementSave)
                {
                    hasBase = false;
                }
            }


            currentBlock = currentBlock.Function("public override void", "StopAnimations", "");

            currentBlock.Line("base.StopAnimations();");

            foreach (var item in elementSave.Instances)
            {
                var itemBase = Gum.Managers.ObjectFinder.Self.GetElementSave(item);
                // Base objects don't have animations (for now)
                if (itemBase is StandardElementSave == false)
                {
                    currentBlock.Line(item.MemberNameInCode() + ".StopAnimations();");
                }
            }
            ElementAnimationsSave animations = GetAnimationsFor(elementSave);
            if (animations != null)
            {
                foreach (var animation in animations.Animations)
                {
                    currentBlock.Line($"{animation.Name}Animation.Stop();");
                }
            }
        }
        private void GenerateInterpolateTo(ElementSave elementSave, ICodeBlock codeBlock, IEnumerable<StateSave> states, string enumName)
        {
            string qualifiedEnum = GueDerivingClassCodeGenerator.GueRuntimeNamespace + "." +
                FlatRedBall.IO.FileManager.RemovePath( elementSave.Name) + "Runtime." + enumName;

            // Make this thing return the Tweener so the uer can customize it
            string parameters = qualifiedEnum + " fromState," + 
                qualifiedEnum + " toState, double secondsToTake, " + 
                "FlatRedBall.Glue.StateInterpolation.InterpolationType interpolationType, FlatRedBall.Glue.StateInterpolation.Easing easing, object owner = null";

            codeBlock = codeBlock.Function("public FlatRedBall.Glue.StateInterpolation.Tweener", "InterpolateTo", parameters);
            {
                codeBlock.Line("FlatRedBall.Glue.StateInterpolation.Tweener tweener = new FlatRedBall.Glue.StateInterpolation.Tweener(from:0, to:1, duration:(float)secondsToTake, type:interpolationType, easing:easing );");
                codeBlock.If("owner == null")
                    .Line("tweener.Owner = this;")
                .End()
                .Else()
                    .Line("tweener.Owner = owner;");

                codeBlock.Line("tweener.PositionChanged = newPosition => this.InterpolateBetween(fromState, toState, newPosition);");
                codeBlock.Line("tweener.Start();");
                codeBlock.Line("StateInterpolationPlugin.TweenerManager.Self.Add(tweener);");
                codeBlock.Line("return tweener;");

            }
        }
        private static void WriteCodeForHasCursorOver(EntitySave entitySave, ICodeBlock codeBlock, bool doesParentHaveCursorOverMethod)
        {
            ICodeBlock func;




            #region Write the method header

            if (doesParentHaveCursorOverMethod)
            {
                func = codeBlock.Function("public override bool", "HasCursorOver", "FlatRedBall.Gui.Cursor cursor");

                func.If("base.HasCursorOver(cursor)")
                    .Line("return true;");
            }
            else
            {
                func = codeBlock.Function("public virtual bool", "HasCursorOver", "FlatRedBall.Gui.Cursor cursor");
            }

            #endregion

            // Even if this has a base Entity, it should check to see
            // if it is paused, invisible, or on an invisible layer.  
            // The reason is if we rely on the base to
            // tell us that, the base will return false if it's paused but
            // we'll still end up checking the clickable objects in this.

            #region Make sure the Entity isn't paused

            func.If("mIsPaused")
                .Line("return false;");

            #endregion

            #region If IVisible, then check to make sure the object is visible
            if (entitySave.ImplementsIVisible)
            {
                func.If("!AbsoluteVisible")
                    .Line("return false;");
            }
            #endregion

            #region Check to make sure the layer this is on is visible

            func.If("LayerProvidedByContainer != null && LayerProvidedByContainer.Visible == false")
                .Line("return false;");

            #endregion

            #region Make sure cursor is on the layer

            func.If("!cursor.IsOn(LayerProvidedByContainer)")
                .Line("return false;");

            #endregion

            AddCodeForIsOn(func, entitySave.NamedObjects);

            func.Line("return false;");
        }
        public override ICodeBlock GenerateAdditionalMethods(ICodeBlock codeBlock, FlatRedBall.Glue.SaveClasses.IElement element)
        {
            //////////////////////////EARLY OUT//////////////////////////////////////
            if (element is ScreenSave)
            {
                return codeBlock;
            }
            ///////////////////////END EARLY OUT/////////////////////////////////////

            bool isInDerived = element.InheritsFromElement();

            if (isInDerived)
            {
                codeBlock = codeBlock.Function("public override void", "MoveToLayer", "FlatRedBall.Graphics.Layer layerToMoveTo");
                codeBlock.Line("base.MoveToLayer(layerToMoveTo);");
            }
            else
            {
                codeBlock = codeBlock.Function("public virtual void", "MoveToLayer", "FlatRedBall.Graphics.Layer layerToMoveTo");
            }


            if (element.InheritsFromFrbType())
            {
                AssetTypeInfo ati = AvailableAssetTypes.Self.GetAssetTypeFromRuntimeType(element.BaseElement);

                if (ati != null )
                {
                    if (ati.RemoveFromLayerMethod != null)
                    {
                        codeBlock.If("LayerProvidedByContainer != null")
                            .Line(ati.RemoveFromLayerMethod.Replace("mLayer", "LayerProvidedByContainer") + ";")
                        .End();
                    }

                    if (ati.LayeredAddToManagersMethod.Count != 0)
                    {
                        codeBlock.Line(ati.LayeredAddToManagersMethod[0].Replace("mLayer", "layerToMoveTo") + ";");
                    }

                }

            }


            foreach (NamedObjectSave nos in element.NamedObjects)
            {
                if (!nos.IsDisabled && !nos.IsContainer)
                {
                    bool shouldCheckForNull = nos.Instantiate == false;



                    if (nos.GetAssetTypeInfo() != null && !string.IsNullOrEmpty(nos.GetAssetTypeInfo().RemoveFromLayerMethod))
                    {
                        NamedObjectSaveCodeGenerator.AddIfConditionalSymbolIfNecesssary(codeBlock, nos);
                        bool shouldSkip = GetShouldSkip(nos);

                        if (!shouldSkip)
                        {

                            if (shouldCheckForNull)
                            {
                                codeBlock = codeBlock.If(nos.InstanceName + " != null");
                            }
                            codeBlock.If("LayerProvidedByContainer != null")
                                .Line(nos.GetAssetTypeInfo().RemoveFromLayerMethod.Replace("this", nos.InstanceName).Replace("mLayer", "LayerProvidedByContainer") + ";")
                            .End();

                            codeBlock.Line(nos.GetAssetTypeInfo().LayeredAddToManagersMethod[0].Replace("this", nos.InstanceName).Replace("mLayer", "layerToMoveTo") + ";");

                            if (shouldCheckForNull)
                            {
                                codeBlock = codeBlock.End();
                            }
                        }
                        NamedObjectSaveCodeGenerator.AddEndIfIfNecessary(codeBlock, nos);
                    }
                    else if (nos.SourceType == SourceType.Entity && !string.IsNullOrEmpty(nos.SourceClassType))
                    {

                        if (shouldCheckForNull)
                        {
                            codeBlock = codeBlock.If(nos.InstanceName + " != null");
                        }
                        NamedObjectSaveCodeGenerator.AddIfConditionalSymbolIfNecesssary(codeBlock, nos);
                        codeBlock.Line(nos.InstanceName + ".MoveToLayer(layerToMoveTo);");
                        NamedObjectSaveCodeGenerator.AddEndIfIfNecessary(codeBlock, nos);


                        if (shouldCheckForNull)
                        {
                            codeBlock = codeBlock.End();
                        }
                    }

                }
            }

            codeBlock.Line("LayerProvidedByContainer = layerToMoveTo;");

            codeBlock = codeBlock.End();

            return codeBlock;
        }
        private static ICodeBlock GetMakeUnusedFactory(ICodeBlock codeBlock, string factoryClassName, bool poolObjects)
        {
            string className = factoryClassName.Substring(0, factoryClassName.Length - "Factory".Length);

            codeBlock.Line("/// <summary>");
            codeBlock.Line("/// Makes the argument objectToMakeUnused marked as unused.  This method is generated to be used");
            codeBlock.Line("/// by generated code.  Use Destroy instead when writing custom code so that your code will behave");
            codeBlock.Line("/// the same whether your Entity is pooled or not.");
            codeBlock.Line("/// </summary>");

            codeBlock = codeBlock
                .Function("public static void", "MakeUnused", className + " objectToMakeUnused")
                    .Line("MakeUnused(objectToMakeUnused, true);")
                .End()
                ._()
                .Line("/// <summary>")
                .Line("/// Makes the argument objectToMakeUnused marked as unused.  This method is generated to be used")
                .Line("/// by generated code.  Use Destroy instead when writing custom code so that your code will behave")
                .Line("/// the same whether your Entity is pooled or not.")
                .Line("/// </summary>")
                .Function("public static void", "MakeUnused", className + " objectToMakeUnused, bool callDestroy");
                    
            if (poolObjects)
            {
                codeBlock
                    .Line("mPool.MakeUnused(objectToMakeUnused);")
                    ._()
                    .If("callDestroy")
                        .Line("objectToMakeUnused.Destroy();")
                    .End();
            }
            else
            {
                // We still need to check if we should call destroy even if not pooled, because the parent may be pooled, in which case an infinite loop
                // can occur if we don't check the callDestroy value. More info on this bug:
                // http://www.hostedredmine.com/issues/413966
                codeBlock
                    .If("callDestroy")
                        .Line("objectToMakeUnused.Destroy();");
            }

            codeBlock = codeBlock.End();

            return codeBlock;
        }
        private static void GenerateSetupCameraMethod(ICodeBlock classContents)
        {
            //internal static void SetupCamera(Camera cameraToSetUp, GraphicsDeviceManager graphicsDeviceManager)

            // for 360, which doesn't support optional parameters.
            ICodeBlock methodContents = classContents.Function(
                "internal static void", 
                "SetupCamera", 
                string.Format("Camera cameraToSetUp, GraphicsDeviceManager graphicsDeviceManager", 
                    ProjectManager.GlueProjectSave.ResolutionWidth,
                    ProjectManager.GlueProjectSave.ResolutionHeight));
            methodContents.Line(string.Format("SetupCamera(cameraToSetUp, graphicsDeviceManager, {0}, {1});", ProjectManager.GlueProjectSave.ResolutionWidth,
                    ProjectManager.GlueProjectSave.ResolutionHeight));



            methodContents = classContents.Function(
                "internal static void",
                "SetupCamera",
                "Camera cameraToSetUp, GraphicsDeviceManager graphicsDeviceManager, int width, int height");


            methodContents.TabCount = 3;

            AddSetResolutionCode(methodContents);

            AddUsePixelCoordinatesCode(methodContents);
        }
        private ICodeBlock GenerateInterpolateToStateAdvanced(ICodeBlock codeBlock, string enumName)
        {
            codeBlock = codeBlock.Function("public void", "InterpolateToState",
                enumName + " fromState, " + enumName + " toState, double secondsToTake, FlatRedBall.Glue.StateInterpolation.InterpolationType interpolationType, FlatRedBall.Glue.StateInterpolation.Easing easing");

            string variableName;
            if (enumName == "VariableState")
            {
                variableName = "CurrentState";
            }
            else
            {
                variableName = "Current" + enumName + "State";
            }

            codeBlock = codeBlock.If("secondsToTake <= 0");
            codeBlock.Line(variableName + " = toState;");
            codeBlock = codeBlock.End().Else();

            // Immediately set the state to the from state:
            codeBlock.Line(variableName + " = fromState;");
            
            codeBlock.Line("mFrom" + enumName + "Tween = fromState;");
            codeBlock.Line("mTo" + enumName + "Tween = toState;");

            codeBlock.Line(
                TweenerNameFor(enumName) + ".Start(0, 1, (float)secondsToTake, FlatRedBall.Glue.StateInterpolation.Tweener.GetInterpolationFunction(interpolationType, easing));");
            codeBlock = codeBlock.End();// else
            codeBlock = codeBlock.End();
            return codeBlock;
        }
Beispiel #53
0
        private static void GenerateRemoveFromManagers(ICodeBlock currentBlock, IElement saveObject)
        {
            if (saveObject.InheritsFromElement())
            {
                currentBlock = currentBlock.Function("public override void", "RemoveFromManagers", "");
                currentBlock.Line("base.RemoveFromManagers();");
            }
            else
            {
                currentBlock = currentBlock.Function("public virtual void", "RemoveFromManagers", "");

            }

            #region Call base.Destroy if it has a derived object

            // The Screen template already includes a call to base.Destroy
            if (saveObject.InheritsFromEntity())
            {
                currentBlock.Line("base.RemoveFromManagers();");
            }

            #endregion

            if (saveObject is EntitySave)
            {
                if (saveObject.InheritsFromFrbType())
                {
                    AssetTypeInfo ati = AvailableAssetTypes.Self.GetAssetTypeFromRuntimeType(saveObject.BaseObject);

                    if (ati != null)
                    {
                        EntitySave asEntitySave = saveObject as EntitySave;

                        if (asEntitySave.CreatedByOtherEntities && !string.IsNullOrEmpty(ati.RecycledDestroyMethod))
                        {
                            currentBlock.Line(ati.RecycledDestroyMethod + ";");
                        }
                        else
                        {
                            currentBlock.Line(ati.DestroyMethod + ";");
                        }
                    }
                }

                else if (!saveObject.InheritsFromElement())
                {
                    currentBlock.Line("FlatRedBall.SpriteManager.ConvertToManuallyUpdated(this);");
                }

                if ((saveObject as EntitySave).ImplementsIWindow && !(saveObject as EntitySave).GetInheritsFromIWindow())
                {
                    currentBlock.Line("FlatRedBall.Gui.GuiManager.RemoveWindow(this);");
                }
            }

            foreach (ElementComponentCodeGenerator codeGenerator in CodeWriter.CodeGenerators)
            {
                codeGenerator.GenerateRemoveFromManagers(currentBlock, saveObject);
            }
        }
        private static void GenerateReloadFileMethod(ICodeBlock currentBlock)
        {
            var reloadFunction = currentBlock
                .Function("public static void", "Reload", "object whatToReload");

            var toLoopThrough = ProjectManager.GlueProjectSave.GlobalFiles.Where(item =>
                item.IsDatabaseForLocalizing == false && item.LoadedAtRuntime &&
                item.IsCsvOrTreatedAsCsv).ToList();

            foreach (var rfs in toLoopThrough)
            {
                var ifInReload = reloadFunction.If("whatToReload == " + rfs.GetInstanceName());
                {
                    ReferencedFileSaveCodeGenerator.GetReload(rfs, null, ifInReload, true, LoadType.MaintainInstance);

                }

            }
        }
Beispiel #55
0
        private static void GenerateReAddToManagers(IElement saveObject, ICodeBlock currentBlock)
        {
            bool isEntity = saveObject is EntitySave;

            bool inheritsFromNonFrbType =
                !string.IsNullOrEmpty(saveObject.BaseElement) && !saveObject.InheritsFromFrbType();

            if (isEntity)
            {
                ICodeBlock reAddToManagers = null;

                if (inheritsFromNonFrbType)
                {
                    reAddToManagers = currentBlock.Function("public override void", "ReAddToManagers", "FlatRedBall.Graphics.Layer layerToAddTo");
                    reAddToManagers.Line("base.ReAddToManagers(layerToAddTo);");
                }
                else
                {
                    reAddToManagers = currentBlock.Function("public virtual void", "ReAddToManagers", "FlatRedBall.Graphics.Layer layerToAddTo");
                    reAddToManagers.Line("LayerProvidedByContainer = layerToAddTo;");

                }

                // add "this" to managers:
                GenerateAddThisEntityToManagers(saveObject, reAddToManagers);

                for (int i = 0; i < saveObject.NamedObjects.Count; i++)
                {
                    NamedObjectSave nos = saveObject.NamedObjects[i];

                    bool setVariables = false;
                    NamedObjectSaveCodeGenerator.WriteAddToManagersForNamedObject(saveObject, nos, reAddToManagers, false, setVariables);
                }
            }
        }
        private static ICodeBlock GetFactoryInitializeMethod(ICodeBlock codeBlock, string factoryClassName, int numberToPreAllocate)
        {
            string entityClassName = factoryClassName.Substring(0, factoryClassName.Length - "Factory".Length);

            codeBlock
                .Function("private static void", "FactoryInitialize", "")
                    .Line("const int numberToPreAllocate = " + numberToPreAllocate + ";")
                    .For("int i = 0; i < numberToPreAllocate; i++")
                        .Line(string.Format("{0} instance = new {0}(mContentManagerName, false);", entityClassName))
                        .Line("mPool.AddToPool(instance);")
                    .End()
                .End();

            return codeBlock;
        }
        private static ICodeBlock GetCreateNewFactoryMethod(ICodeBlock codeBlock, string className, bool poolObjects, string baseEntityName)
        {
            className = className.Substring(0, className.Length - "Factory".Length);

            // no tabs needed on first line
            codeBlock
                .Function(StringHelper.SpaceStrings("public", "static", className), "CreateNew", "")
                    .Line("return CreateNew(null);")
                .End();

            codeBlock = codeBlock
                .Function(StringHelper.SpaceStrings("public", "static", className), "CreateNew", "Layer layer")
                    .If("string.IsNullOrEmpty(mContentManagerName)")
                        .Line("throw new System.Exception(\"You must first initialize the factory to use it.\");")
                    .End()

                    .Line(className + " instance = null;");

            if (poolObjects)
            {
                codeBlock
                    .Line("instance = mPool.GetNextAvailable();")
                    .If("instance == null")
                        .Line("mPool.AddToPool(new " + className + "(mContentManagerName, false));")
                        .Line("instance =  mPool.GetNextAvailable();")
                    .End()
                    .Line("instance.AddToManagers(layer);");
            }
            else
            {
                codeBlock
                    .Line(string.Format("instance = new {0}(mContentManagerName, false);", className))
                    .Line("instance.AddToManagers(layer);");
            }

            CreateAddToListIfNotNullCode(codeBlock, "mScreenListReference");

            if (!string.IsNullOrEmpty(baseEntityName))
            {
                CreateAddToListIfNotNullCode(codeBlock, "mBaseScreenListReference");
            }

            codeBlock = codeBlock
                .If("EntitySpawned != null")
                    .Line("EntitySpawned(instance);")
                .End()
                .Line("return instance;")
            .End();

            return codeBlock;
        }
        private void GenerateInterpolateToFromCurrent(ICodeBlock currentBlock, string enumType, bool isRelative)
        {
            string functionName = "InterpolateTo";

            string whereToLook = "States";

            if(enumType != "VariableState")
            {
                whereToLook = $"Categories.First(item => item.Name == \"{enumType}\").States";
            }


            string toStateRightSide = $"this.ElementSave.{whereToLook}.First(item => item.Name == toState.ToString());";

            if(isRelative)
            {
                functionName = "InterpolateToRelative";

                toStateRightSide = "AddToCurrentValuesWithState(toState);";
            }

            currentBlock = currentBlock.Function("public FlatRedBall.Glue.StateInterpolation.Tweener", functionName,
                enumType + " toState, double secondsToTake, FlatRedBall.Glue.StateInterpolation.InterpolationType interpolationType, FlatRedBall.Glue.StateInterpolation.Easing easing, object owner = null ");



            currentBlock.Line("Gum.DataTypes.Variables.StateSave current = GetCurrentValuesOnState(toState);");

            currentBlock.Line("Gum.DataTypes.Variables.StateSave toAsStateSave = " + toStateRightSide);

            currentBlock.Line("FlatRedBall.Glue.StateInterpolation.Tweener tweener = new FlatRedBall.Glue.StateInterpolation.Tweener(from: 0, to: 1, duration: (float)secondsToTake, type: interpolationType, easing: easing);");
            currentBlock.If("owner == null")
                .Line("tweener.Owner = this;")
            .End()
            .Else()
                .Line("tweener.Owner = owner;");

            currentBlock.Line("tweener.PositionChanged = newPosition => this.InterpolateBetween(current, toAsStateSave, newPosition);");

            string variableName;
            if(enumType == "VariableState")
            {
                variableName = "CurrentVariableState";
            }
            else
            {
                variableName = $"Current{enumType}State";
            }

            currentBlock.Line($"tweener.Ended += ()=> this.{variableName} = toState;");
            currentBlock.Line("tweener.Start();");

            currentBlock.Line("StateInterpolationPlugin.TweenerManager.Self.Add(tweener);");
            currentBlock.Line("return tweener;");
        }
        private static ICodeBlock GetInitializeFactoryMethod(ICodeBlock codeBlock, string className, bool poolObjects, string listToAssign)
        {
            codeBlock = codeBlock
                .Function("public static void", "Initialize", string.Format("FlatRedBall.Math.PositionedObjectList<{0}> listFromScreen, string contentManager", className))
                    .Line("mContentManagerName = contentManager;")
                    .Line(listToAssign + " = listFromScreen;");

            if (poolObjects)
            {
                codeBlock.Line("FactoryInitialize();");
            }

            codeBlock = codeBlock.End();

            return codeBlock;
        }
        private static bool GenerateLoadAsyncCode(ICodeBlock classLevelBlock, ICodeBlock initializeBlock)
        {
            bool loadAsync = ProjectManager.GlueProjectSave.GlobalContentSettingsSave.LoadAsynchronously;

            if (loadAsync)
            {
                GenerateInitializeAsync(initializeBlock);
            }

            loadAsync = ProjectManager.GlueProjectSave.GlobalContentSettingsSave.LoadAsynchronously;
            if (loadAsync)
            {

                classLevelBlock._();


                classLevelBlock.Line("#if !REQUIRES_PRIMARY_THREAD_LOADING");

                classLevelBlock
                    .Function("static void", "RequestContentLoad", "string contentName")
                        .Lock("LoadMethodList")
                            .Line("int index = -1;")
                            .For("int i = 0; i < LoadMethodList.Count; i++")
                                .If("LoadMethodList[i].Name == contentName")
                                    .Line("index = i;")
                                    .Line("break;")
                                .End()
                            .End()
                            .If("index != -1")
                                .Line("NamedDelegate delegateToShuffle = LoadMethodList[index];")
                                .Line("LoadMethodList.RemoveAt(index);")
                                .Line("LoadMethodList.Insert(0, delegateToShuffle);")
                            .End()
                        .End()
                    .End();
                classLevelBlock.Line("#endif");

                classLevelBlock._();

                classLevelBlock.Line("#if !REQUIRES_PRIMARY_THREAD_LOADING");
                classLevelBlock
                    .Function("static void", "AsyncInitialize", "")

                        .Line("#if XBOX360")
                        .Line("// We can not use threads 0 or 2")
                        .Line("// Async screen loading uses thread 4, so we'll use 3 here")
                        .Line("Thread.CurrentThread.SetProcessorAffinity(3);")
                        .Line("#endif")

                        .Line("bool shouldLoop = LoadMethodList.Count != 0;")

                        .While("shouldLoop")
                            .Line("System.Action action = null;")
                            .Lock("LoadMethodList")

                                .Line("action = LoadMethodList[0].LoadMethod;")
                                .Line("LoadMethodList.RemoveAt(0);")
                                .Line("shouldLoop = LoadMethodList.Count != 0 && !ShouldStopLoading;")

                            .End()
                            .Line("action();")
                        .End()
                        .Line("IsInitialized = true;")
                        ._()
                    .End();
                classLevelBlock.Line("#endif");

                //stringBuilder.AppendLine("\t\t\tstring ContentManagerName = \"Global\";");

            }

            return loadAsync;
        }