protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // hide title bar. this.RequestWindowFeature(global::Android.Views.WindowFeatures.NoTitle); // initialize OsmSharp native handlers. Native.Initialize(); // initialize map. var map = new Map(); // add a preprocessed vector data file. var sceneStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(@"Android.Vectors.default.map"); map.AddLayer(new LayerScene(Scene2D.Deserialize(sceneStream, true))); // define the mapview. _mapView = new MapView(this, new MapViewSurface(this)); _mapView.Map = map; _mapView.MapMaxZoomLevel = 17; // limit min/max zoom, the vector data in this sample covers only a small area. _mapView.MapMinZoomLevel = 12; _mapView.MapTilt = 0; _mapView.MapCenter = new GeoCoordinate(51.26361, 4.78620); _mapView.MapZoom = 16; _mapView.MapAllowTilt = false; // set the map view as the default content view. SetContentView(_mapView); }
void ApplyScene() { int lw = (int)model.data.sizeDelta.x; int lh = (int)model.data.sizeDelta.y; if (Scene == null) { Scene = new Scene2D(); Scene.TextureMode = true; Scene.ReSize(lw, lh); offset += 100; Scene.Root.position = new Vector3(offset, 0, 0); Context.texture = Scene.texture; } else { if (w != lw | h != lh) { Scene.ReSize(w, h); Context.texture = Scene.texture; } } w = lw; h = lh; }
/// <summary> /// Renders the given scene on the given target for the given view. /// </summary> /// <param name="orginalTarget"></param> /// <param name="scene">Scene.</param> /// <param name="view">View.</param> public bool Render(TTarget orginalTarget, Scene2D scene, View2D view) { var scenes = new List <Scene2D>(); scenes.Add(scene); return(this.Render(orginalTarget, scenes, view)); }
/// <summary> /// Initializes a new instance of the <see cref="OsmSharp.Android.UI.CanvasRenderer2DView"/> class. /// </summary> /// <param name="context">Context.</param> public CanvasRenderer2DView(Context context, Scene2D scene) : base(context) { Initialize(); this.Scene = scene; }
protected void Awake() { if (isMain) { main = this; } }
public override void ViewDidLoad() { base.ViewDidLoad(); // initialize OsmSharp native handlers. Native.Initialize(); // initialize map. var map = new Map(); // add a preprocessed vector data file. var sceneStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(@"iOS.Vectors.default.map"); map.AddLayer(new LayerScene(Scene2D.Deserialize(sceneStream, true))); // define the mapview. _mapView = new MapView(); _mapView.Map = map; _mapView.MapMaxZoomLevel = 17; // limit min/max zoom, the vector data in this sample covers only a small area. _mapView.MapMinZoomLevel = 12; _mapView.MapTilt = 0; _mapView.MapCenter = new GeoCoordinate(51.26361, 4.78620); _mapView.MapZoom = 16; _mapView.MapAllowTilt = false; View = _mapView; }
/// <summary> /// Initializes a new instance of the <see cref="OsmSharp.Android.UI.CanvasRenderer2DView"/> class. /// </summary> /// <param name="context">Context.</param> /// <param name="attrs">Attrs.</param> public CanvasRenderer2DView(Context context, IAttributeSet attrs, Scene2D scene) : base(context, attrs) { Initialize(); this.Scene = scene; }
/// <summary> /// Initialize implementation from IMapView. /// </summary> /// <param name="mapLayout"></param> void IMapViewSurface.Initialize(MapView mapLayout) { // create the Open GL 2D target. _target = new OpenGLTarget2D(); this.SetRenderer(_target); _mapView = mapLayout; this.SetWillNotDraw(false); this.MapMinZoomLevel = 10; this.MapMaxZoomLevel = 20; // create the renderer. _renderer = new MapRenderer <OpenGLTarget2D>( new OpenGLRenderer2D()); // initialize the gesture detection. this.SetOnTouchListener(this); _scaleGestureDetector = new ScaleGestureDetector( this.Context, this); _rotateGestureDetector = new RotateGestureDetector( this.Context, this); _moveGestureDetector = new MoveGestureDetector( this.Context, this); _tagGestureDetector = new TapGestureDetector( this.Context, this); _makerLayer = new LayerPrimitives( new WebMercator()); _scene = new Scene2D(new WebMercator(), 16); _scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value; }
public static Scene2D SpinStateKeyBoardTest() { const string SPIN_CW = "Spin CW"; const string SPIN_CCW = "Spin CCW"; const float delta = (float)(-360.0f * Math.PI / 180.0); State spinCWState = new State(SPIN_CW); spinCWState.Add(new ActionSpin(0.0f, 0.0f, -delta)); spinCWState.Add(new EventKeyBoard(SPIN_CCW, Keys.D)); State spinCCWState = new State(SPIN_CCW); spinCCWState.Add(new ActionSpin(0.0f, 0.0f, delta)); spinCCWState.Add(new EventKeyBoard(SPIN_CW, Keys.A)); Behavior behavior = new Behavior(); behavior.Add(spinCWState); behavior.Add(spinCCWState); Sprite sprite = new Sprite(FACE_IMAGE); sprite.Add(behavior); Scene2D scene = new Scene2D(); scene.Add(sprite); return(scene); }
/// <summary> /// Creates a new MapCSS scene target. /// </summary> /// <param name="styleInterpreter"></param> /// <param name="scene"></param> /// <param name="projection"></param> public StyleOsmStreamSceneTarget(StyleInterpreter styleInterpreter, Scene2D scene, IProjection projection) { _projection = projection; _scene = scene; _styleInterpreter = styleInterpreter; }
/// <summary> /// Creates a new RTreeSerializer. /// </summary> /// <param name="scene"></param> /// <param name="compressed"></param> /// <param name="sceneAt"></param> public SceneObjectRTreeSerializer(Scene2D scene, bool compressed, int sceneAt, int scaleFactor) { _scaleFactor = scaleFactor; _sceneAt = sceneAt; _compressed = compressed; _scene = scene; }
public void TestMapCSSArea() { MemoryDataSource source = new MemoryDataSource( Node.Create(1, 0, 0), Node.Create(2, 1, 0), Node.Create(3, 0, 1), Way.Create(1, new TagsCollection( Tag.Create("area", "yes")), 1, 2, 3, 1)); // test closed way. string css = "area { " + " fill-color: black; " + "} "; // create the projection and scene objects. var mercator = new WebMercator(); Scene2D scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16); // create the projection and scene objects. scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16); // create the interpreter. MapCSSInterpreter interpreter = new MapCSSInterpreter(css, new MapCSSDictionaryImageSource()); interpreter.Translate(scene, mercator, source, source.GetWay(1)); // test the scene contents. Assert.AreEqual(1, scene.Count); Primitive2D primitive = scene.Get(0); Assert.IsInstanceOf <Polygon2D>(primitive); }
public Window2D(Scene2D scene, GameWindowSettings gameWindowSettings, NativeWindowSettings nativeWindowSettings) : base(gameWindowSettings, nativeWindowSettings) { Scene = scene; eventContext = new EventContext(); }
/// <summary> /// Translates a multipolygon. /// </summary> /// <param name="scene">The scene to add primitives to.</param> /// <param name="projection">The projection used to convert the objects.</param> /// <param name="multiPolygon"></param> private void TranslateMultiPolygon(Scene2D scene, IProjection projection, MultiPolygon multiPolygon) { foreach (Polygon polygon in multiPolygon) { polygon.Attributes = multiPolygon.Attributes; this.TranslatePolygon(scene, projection, polygon); } }
/// <summary> /// Creates a new MapCSS scene target. /// </summary> /// <param name="mapCSSInterpreter"></param> /// <param name="sceneStream"></param> /// <param name="scene"></param> /// <param name="projection"></param> public StyleOsmStreamSceneTarget(StyleInterpreter mapCSSInterpreter, Stream sceneStream, Scene2D scene, IProjection projection) { _projection = projection; _scene = scene; _sceneStream = sceneStream; _mapCSSInterpreter = mapCSSInterpreter; }
/// <summary> /// Creates a new MapCSS scene target. /// </summary> /// <param name="styleInterpreter"></param> /// <param name="scene"></param> /// <param name="projection"></param> /// <param name="stream"></param> public StyleOsmStreamSceneStreamTarget(StyleInterpreter styleInterpreter, Scene2D scene, IProjection projection, Stream stream) { _projection = projection; _scene = scene; _styleInterpreter = styleInterpreter; _stream = stream; }
/// <summary> /// Renders the primities for the given scene. /// </summary> /// <param name="target"></param> /// <param name="scene"></param> /// <param name="view"></param> private bool RenderPrimitives(Target2DWrapper <TTarget> target, Scene2D scene, View2D view) { // TODO: calculate zoom. float zoom = (float)view.CalculateZoom(target.Width, target.Height); // loop over all primitives in the scene. foreach (Scene2DPrimitive scenePrimitive in scene.Get(view, zoom)) { // the primitive is visible. IScene2DPrimitive primitive = scenePrimitive.Primitive; if (_cancelFlag) { return(false); // stop rendering on cancel and return false for an incomplete rendering. } if (primitive is Point2D) { var point = (Point2D)(primitive); this.DrawPoint(target, point.X, point.Y, point.Color, this.FromPixels(target, view, point.Size)); } else if (primitive is Line2D) { var line = (Line2D)(primitive); this.DrawLine(target, line.X, line.Y, line.Color, this.FromPixels(target, view, line.Width), line.LineJoin, line.Dashes); } else if (primitive is Polygon2D) { var polygon = (Polygon2D)(primitive); this.DrawPolygon(target, polygon.X, polygon.Y, polygon.Color, this.FromPixels(target, view, polygon.Width), polygon.Fill); } else if (primitive is Icon2D) { var icon = (Icon2D)(primitive); this.DrawIcon(target, icon.X, icon.Y, icon.Image); } else if (primitive is Image2D) { var image = (Image2D)(primitive); image.Tag = this.DrawImage(target, image.Left, image.Top, image.Right, image.Bottom, image.ImageData, image.Tag); } else if (primitive is Text2D) { var text = (Text2D)(primitive); this.DrawText(target, text.X, text.Y, text.Text, text.Color, this.FromPixels(target, view, text.Size), text.HaloColor, text.HaloRadius, text.Font); } else if (primitive is LineText2D) { var lineText = (LineText2D)(primitive); this.DrawLineText(target, lineText.X, lineText.Y, lineText.Text, lineText.Color, this.FromPixels(target, view, lineText.Size), lineText.HaloColor, lineText.HaloRadius, lineText.Font); } } return(true); }
/// <summary> /// Called when the mapview has changed. /// </summary> /// <param name="map"></param> /// <param name="zoomFactor"></param> /// <param name="center"></param> /// <param name="view"></param> public void ViewChanged(Map map, float zoomFactor, GeoCoordinate center, View2D view) { // calculate the current zoom level. var zoomLevel = (int)System.Math.Round(map.Projection.ToZoomLevel(zoomFactor), 0); // build the boundingbox. var box = new GeoCoordinateBox( map.Projection.ToGeoCoordinates(view.Left, view.Top), map.Projection.ToGeoCoordinates(view.Right, view.Bottom)); // build the tile range. TileRange range = TileRange.CreateAroundBoundingBox(box, zoomLevel); DateTime now = DateTime.Now; // build the new scene. Scene2D newScene = new Scene2D(); if (_connection.State == System.Data.ConnectionState.Closed) { _connection.Open(); } lock (_connection) { // make sure the connection is accessed synchronously. // TODO: Investigate the SQLite multithreaded behaviour.. // TODO: this a very naive way of loading these tiles. Find a way to query SQLite more efficiently // TODO: find a way to have some cached tiles. foreach (var tile in range) { Tile invertTile = tile.InvertY(); SQLiteCommand command = new SQLiteCommand("SELECT * FROM tiles WHERE zoom_level = :zoom_level AND tile_column = :tile_column AND tile_row = :tile_row;", _connection); command.Parameters.AddWithValue("zoom_level", invertTile.Zoom); command.Parameters.AddWithValue("tile_column", invertTile.X); command.Parameters.AddWithValue("tile_row", invertTile.Y); using (var tileReader = command.ExecuteReader()) { while (tileReader.Read()) { //Tile readTile = new Tile((int)tileReader["tile_column"], // (int)tileReader["tile_row"], (int)tileReader["zoom_level"]); float minZoom = (float)map.Projection.ToZoomFactor(tile.Zoom - 0.5f); float maxZoom = (float)map.Projection.ToZoomFactor(tile.Zoom + 0.5f); float left = (float)map.Projection.LongitudeToX(tile.TopLeft.Longitude); float right = (float)map.Projection.LongitudeToX(tile.BottomRight.Longitude); float bottom = (float)map.Projection.LatitudeToY(tile.BottomRight.Latitude); float top = (float)map.Projection.LatitudeToY(tile.TopLeft.Latitude); newScene.AddImage(0, minZoom, maxZoom, left, top, right, bottom, (byte[])tileReader["tile_data"]); } } } this.Scene = newScene; } }
/// <summary> /// Creates a new OSM data layer. /// </summary> /// <param name="dataSource"></param> /// <param name="styleInterpreter"></param> public LayerGraph(IRoutingAlgorithmData <Edge> dataSource, StyleInterpreter styleInterpreter) { _dataSource = dataSource; _styleInterpreter = styleInterpreter; _scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16); _interpretedObjects = new Dictionary <int, HashSet <ArcId> >(); }
public void AddToScene(Scene2D scene2D) { AptPalantir.Reset(); _window = _game.LoadAptWindow("Palantir.apt"); _root = _window.Root; _game.Scene2D.AptWindowManager.PushWindow(_window); }
/// <summary> /// Creates a new OSM data layer. /// </summary> /// <param name="dataSource"></param> /// <param name="styleInterpreter"></param> public LayerDynamicGraphLiveEdge(IBasicRouterDataSource <LiveEdge> dataSource, StyleInterpreter styleInterpreter) { _dataSource = dataSource; _styleInterpreter = styleInterpreter; _scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16); _interpretedObjects = new Dictionary <int, HashSet <ArcId> >(); }
/// <summary> /// Builds a merged version of the given scene object. /// </summary> /// <param name="other"></param> /// <returns></returns> public Scene2D BuildMergedScene(Scene2D other) { Scene2D target = new Scene2D(new WebMercator(), other.GetZoomFactors().ToList(), true); for (int idx = 0; idx < other.GetZoomFactors().Length; idx++) { this.MergeObjects(target, other, idx); } return target; }
/// <summary> /// Raises the OnLoad event. /// </summary> /// <param name="e"></param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); // initialize mapcss interpreter. var mapCSSInterpreter = new MapCSSInterpreter( new FileInfo(@"D:\Dropbox\Dropbox\SharpSoftware\Projects\Eurostation ReLive\Server_Dropbox\OSM\static\default.mapcss").OpenRead(), new MapCSSDictionaryImageSource()); // initialize map. var map = new OsmSharp.UI.Map.Map(); //// initialize router. //_router = Router.CreateLiveFrom(new OsmSharp.Osm.PBF.Streams.PBFOsmStreamSource( // new FileInfo(@"kempen.osm.pbf").OpenRead()), new OsmRoutingInterpreter()); var scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), new List <float>(new float[] { 16, 14, 12, 10 })); var target = new StyleOsmStreamSceneTarget( mapCSSInterpreter, scene, new WebMercator()); var source = new XmlOsmStreamSource( new FileInfo(@"D:\Dropbox\Dropbox\SharpSoftware\Projects\Eurostation ReLive\Server_Dropbox\OSM\relive_mechelen\mechelen_new.osm").OpenRead()); var progress = new OsmStreamFilterProgress(); progress.RegisterSource(source); target.RegisterSource(progress); target.Pull(); //var merger = new Scene2DObjectMerger(); //scene = merger.BuildMergedScene(scene); map.AddLayer(new LayerScene(scene)); //var dataSource = MemoryDataSource.CreateFromXmlStream( // new FileInfo(@"D:\Dropbox\Dropbox\SharpSoftware\Projects\Eurostation ReLive\Server_Dropbox\OSM\relive_mechelen\mechelen_new.osm").OpenRead()); //map.AddLayer(new LayerOsm(dataSource, mapCSSInterpreter, map.Projection)); //var layerTile = new LayerTile(@"http://otile1.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpg", 200); //layerTile.MinZoom = 12; //layerTile.MaxZoom = 13; //map.AddLayer(layerTile); //map.AddLayer(new LayerScene( // Scene2D.Deserialize(new FileInfo(@"default.map").OpenRead(), // true))); // initialize route/points layer. _layerRoute = new LayerRoute(new OsmSharp.Math.Geo.Projections.WebMercator()); map.AddLayer(_layerRoute); _layerPrimitives = new LayerPrimitives(new OsmSharp.Math.Geo.Projections.WebMercator()); map.AddLayer(_layerPrimitives); // set control properties. this.mapControl1.Map = map; this.mapControl1.MapCenter = new GeoCoordinate(51.0167, 4.4914); // wechel this.mapControl1.MapZoom = 14; this.mapControl1.MapMouseClick += mapControl1_MapMouseClick; this.mapControl1.MapMouseMove += mapControl1_MapMouseMove; }
public virtual void Draw2DScene(Scene2D CurrentScene, int Width, int Height) { if (CurrentScene == null) { return; } this._CurrentRenderer.Toggle(RenderEnableCap.Depth, false); String LibPath = "Data\\"; if (!this._CurrentRenderer.IsMaterialReady("2D")) { string Vertex2D = File.ReadAllText(LibPath + "GLSL\\Generator\\Vertex2D.shader"); string Fragment2D = File.ReadAllText(LibPath + "GLSL\\Generator\\Fragment2D.shader"); this._CurrentRenderer.SetMaterial(new object[3] { new string[6] { "2D", Vertex2D, Fragment2D, null, null, null }, null, null }, true); } this._CurrentRenderer.SetViewport(Width, Height); this._CurrentRenderer.ClearColor(new float[4] { (CurrentScene.BackColor.R * 1.0f + 1) / 256, (CurrentScene.BackColor.G * 1.0f + 1) / 256, (CurrentScene.BackColor.B * 1.0f + 1) / 256, (CurrentScene.BackColor.A * 1.0f + 1) / 256 }); this._CurrentRenderer.Clear(); this._Matrix.MatrixMode("Projection"); this._Matrix.LoadIdentity(); this._Matrix.Ortho2D(0, Width, Height, 0); this._CurrentRenderer.SetProjectionMatrix(_Matrix.ProjectionMatrix); this._Matrix.MatrixMode("ModelView"); this._Matrix.LoadIdentity(); this._Matrix.Translate(CurrentScene.Transformation.Translation.X, CurrentScene.Transformation.Translation.Y, CurrentScene.Transformation.Translation.Z); this._Matrix.Scale(CurrentScene.Transformation.Scale.X, CurrentScene.Transformation.Scale.Y, CurrentScene.Transformation.Scale.Z); this._Matrix.PushMatrix(); this._CurrentRenderer.SetModelViewMatrix(_Matrix.ModelViewMatrix); if (this._CurrentRenderer.TargetType == RenderTargetType.Editor) { this._CurrentRenderer.Render2DGrid(); } for (int i = 0; i < CurrentScene.Objects.Count; i++) { if (CurrentScene.Objects[i].Visual.Type == DrawObjectType.Sprite) { DrawSprite((Sprite)CurrentScene.Objects[i].Visual); } if (CurrentScene.Objects[i].Visual.Type == DrawObjectType.Tile) { DrawTile((Tile)CurrentScene.Objects[i].Visual); } } }
public void AddToScene(Game game, Scene2D scene, bool useShellMap) { var aptWindow = game.LoadAptWindow(_aptFileName); if (!useShellMap) { aptWindow.BackgroundImage = game.AssetStore.MappedImages.GetByName(_fallbackShell); } scene.AptWindowManager.PushWindow(aptWindow); }
public void AddToScene(ContentManager contentManager, Scene2D scene, bool useShellMap) { var aptWindow = contentManager.Load <AptWindow>(_aptFileName); if (!useShellMap) { aptWindow.BackgroundImage = aptWindow.ImageLoader.GetMappedImage(_fallbackShell); } scene.AptWindowManager.PushWindow(aptWindow); }
/// <summary> /// Dispose the specified disposing. /// </summary> /// <param name="disposing">If set to <c>true</c> disposing.</param> protected override void Dispose(bool disposing) { base.Dispose(disposing); _cachedScene.Clear(); _cachedScene = null; _renderingThread.Abort(); _renderingThread = null; _bytescache = null; }
public LevelScreen(IGameObjectsFactory gameObjectsFactory, IUserInterfaceFactory interfaceFactory, IMathFunctionsFactory functionsFactory, ICamera2D camera2D, IContentLoader contentLoader) { this.contentLoader = contentLoader; this.camera = camera2D; player = new Player(); this.objectsFactory = gameObjectsFactory; scene2d = new Scene2D(gameObjectsFactory, new GameplayFactory(gameObjectsFactory), interfaceFactory); this.functionsFactory = functionsFactory; }
/// <summary> /// Tests interpreting all data from a given pbf source. /// </summary> /// <param name="name"></param> /// <param name="mapCSS"></param> /// <param name="scene"></param> /// <param name="pbfSource"></param> public static void TestInterpret(string name, string mapCSS, Scene2D scene, string pbfSource) { FileInfo cssFile = new FileInfo(string.Format(@".\TestFiles\{0}", mapCSS)); Stream cssStream = cssFile.OpenRead(); MapCSSInterpreter interpreter = new MapCSSInterpreter(cssStream, new MapCSSDictionaryImageSource()); MapCSSInterpreterTests.TestInterpret(name, interpreter, scene, pbfSource); cssStream.Dispose(); }
/// <summary> /// Builds a merged version of the given scene object. /// </summary> /// <param name="other"></param> /// <returns></returns> public Scene2D BuildMergedScene(Scene2D other) { Scene2D target = new Scene2D(new WebMercator(), other.GetZoomFactors().ToList(), true); for (int idx = 0; idx < other.GetZoomFactors().Length; idx++) { this.MergeObjects(target, other, idx); } return(target); }
/// <summary> /// Renders the given scene on the given target for the given view. /// </summary> /// <param name="orginalTarget"></param> /// <param name="scenes">Scene.</param> /// <param name="view">View.</param> public bool Render(TTarget orginalTarget, List <Scene2D> scenes, View2D view) { this.SetRunning(true); if (view == null) { throw new ArgumentNullException("view"); } if (scenes == null) { throw new ArgumentNullException("scenes"); } if (orginalTarget == null) { throw new ArgumentNullException("orginalTarget"); } // create the target wrapper. Target2DWrapper <TTarget> target = this.CreateTarget2DWrapper(orginalTarget); // the on before render event. this.OnBeforeRender(target, scenes, view); // transform the target coordinates or notify the target of the // view coordinate system. this.Transform(target, view); // draw the backcolor. this.DrawBackColor(target, scenes[0].BackColor); bool complete = true; foreach (var scene in scenes) { // render the primitives. complete = complete && this.RenderPrimitives(target, scene, view); if (!complete) { break; } } // the on after render event. this.OnAfterRender(target, scenes, view); // build a cached version. _cachedScene = this.BuildSceneCache(target, _cachedScene, scenes, view); this.SetRunning(false); return(complete); }
public static Scene2D FlipBookTest() { const float FLIP_AMOUNT = (float)(180.0f * Math.PI / 180.0); const string FLIP_STATE = "Flip"; string[] IDLE_IMAGE = new string[] { NINJA_ACTION + "Idle__000.png", NINJA_ACTION + "Idle__001.png", NINJA_ACTION + "Idle__002.png", NINJA_ACTION + "Idle__003.png", NINJA_ACTION + "Idle__004.png", NINJA_ACTION + "Idle__005.png", NINJA_ACTION + "Idle__006.png", NINJA_ACTION + "Idle__007.png", NINJA_ACTION + "Idle__008.png", NINJA_ACTION + "Idle__009.png" }; string[] JUMP_IMAGE = new string[] { NINJA_ACTION + "Jump__000.png", NINJA_ACTION + "Jump__001.png", NINJA_ACTION + "Jump__002.png", NINJA_ACTION + "Jump__003.png", NINJA_ACTION + "Jump__004.png", NINJA_ACTION + "Jump__005.png", NINJA_ACTION + "Jump__006.png", NINJA_ACTION + "Jump__007.png", NINJA_ACTION + "Jump__008.png", NINJA_ACTION + "Jump__009.png" }; FlipBook fb = new FlipBook(IDLE_IMAGE); State state = new State(FLIP_STATE); state.Add(new ActionSetRotate(FLIP_AMOUNT, 0.0f, 0.0f)); state.Add(new ActionTranslate(0.5f)); Behavior behavior = new Behavior(); behavior.Add(state); Sprite sprite = new Sprite(fb, behavior); Scene2D scene = new Scene2D(); scene.Add(sprite); return(scene); }
/// <summary> /// Builds a merged version of the given scene object. /// </summary> /// <param name="other"></param> /// <returns></returns> public Scene2D BuildMergedScene(Scene2D other) { // build new scene and copy some relevant configurations. var target = new Scene2D(new WebMercator(), other.GetZoomFactors().ToList(), true); target.BackColor = other.BackColor; // merge objects per zoom factor. for (int idx = 0; idx < other.GetZoomFactors().Length; idx++) { this.MergeObjects(target, other, idx); } return target; }
/// <summary> /// Merges objects from the given scene for the given zoom level. /// </summary> /// <param name="target"></param> /// <param name="source"></param> /// <param name="idx"></param> private void MergeObjects(Scene2D target, Scene2D source, int idx) { Dictionary<Scene2D.ScenePoints, Scene2DStylesSet> lines = new Dictionary<Scene2D.ScenePoints, Scene2DStylesSet>(); Dictionary<PointF2D, HashSet<Scene2D.ScenePoints>> endpoints = new Dictionary<PointF2D, HashSet<Scene2D.ScenePoints>>(); Dictionary<uint, SceneObject> sceneObjects = source.GetSceneObjectsAt(idx); foreach (var sceneObject in sceneObjects) { if (sceneObject.Value.Enum == SceneObjectType.LineObject) { // the scene object is a line object. var sceneLineObject = sceneObject.Value as SceneLineObject; Scene2D.ScenePoints scenePoints = source.GetPoints(sceneLineObject.GeoId); Scene2DStylesSet stylesSet = null; if (!lines.TryGetValue(scenePoints, out stylesSet)) { // create styles set. stylesSet = new Scene2DStylesSet(); lines.Add(scenePoints, stylesSet); } stylesSet.AddStyleLine(sceneLineObject.StyleId); //var sceneLineObject = (sceneObject.Value as SceneLineObject); //Scene2D.ScenePoints scenePoints = source.GetPoints(sceneLineObject.GeoId); //StyleLine styleLine = source.GetStyleLine(sceneLineObject.StyleId); //uint? pointsId = target.AddPoints(scenePoints.X, scenePoints.Y); //if (pointsId.HasValue) //{ // target.AddStyleLine(pointsId.Value, styleLine.Layer, styleLine.MinZoom, styleLine.MaxZoom, // styleLine.Color, styleLine.Width, styleLine.LineJoin, styleLine.Dashes); //} } else if (sceneObject.Value.Enum == SceneObjectType.LineTextObject) { var sceneLineTextObject = sceneObject.Value as SceneLineTextObject; Scene2D.ScenePoints scenePoints = source.GetPoints(sceneLineTextObject.GeoId); Scene2DStylesSet stylesSet = null; if (!lines.TryGetValue(scenePoints, out stylesSet)) { // create styles set. stylesSet = new Scene2DStylesSet(); lines.Add(scenePoints, stylesSet); } stylesSet.AddStyleLineText(sceneLineTextObject.StyleId, sceneLineTextObject.TextId); //var sceneLineTextObject = (sceneObject.Value as SceneLineTextObject); //Scene2D.ScenePoints scenePoints = source.GetPoints(sceneLineTextObject.GeoId); //StyleText styleText = source.GetStyleText(sceneLineTextObject.StyleId); //string text = source.GetText(sceneLineTextObject.TextId); //uint? pointsId = target.AddPoints(scenePoints.X, scenePoints.Y); //if (pointsId.HasValue) //{ // target.AddStyleLineText(pointsId.Value, styleText.Layer, styleText.MinZoom, styleText.MaxZoom, // styleText.Color, styleText.Size, text, styleText.Font, styleText.HaloColor, styleText.HaloRadius); //} } else if (sceneObject.Value.Enum == SceneObjectType.IconObject) { throw new NotSupportedException("Icons not yet supported!"); //var sceneIconObject = (sceneObject.Value as SceneIconObject); //Scene2D.ScenePoint scenePoint = source.GetPoint(sceneIconObject.GeoId); //source.GetStyleIcon( //target.AddIcon(target.AddPoint(scenePoint.X, scenePoint.Y); } else if (sceneObject.Value.Enum == SceneObjectType.PointObject) { var scenePointObject = (sceneObject.Value as ScenePointObject); Scene2D.ScenePoint scenePoint = source.GetPoint(scenePointObject.GeoId); StylePoint stylePoint = source.GetStylePoint(scenePointObject.StyleId); target.AddStylePoint(target.AddPoint(scenePoint.X, scenePoint.Y), stylePoint.Layer, stylePoint.MinZoom, stylePoint.MaxZoom, stylePoint.Color, stylePoint.Size); } else if (sceneObject.Value.Enum == SceneObjectType.PolygonObject) { var scenePolygonObject = (sceneObject.Value as ScenePolygonObject); Scene2D.ScenePoints scenePoints = source.GetPoints(sceneObject.Value.GeoId); StylePolygon stylePolygon = source.GetStylePolygon(sceneObject.Value.StyleId); uint? pointsId = target.AddPoints(scenePoints.X, scenePoints.Y); if (pointsId.HasValue) { target.AddStylePolygon(pointsId.Value, stylePolygon.Layer, stylePolygon.MinZoom, stylePolygon.MaxZoom, stylePolygon.Color, stylePolygon.Width, stylePolygon.Fill); } } else if (sceneObject.Value.Enum == SceneObjectType.TextObject) { var sceneTextObject = (sceneObject.Value as SceneTextObject); Scene2D.ScenePoint scenePoint = source.GetPoint(sceneObject.Value.GeoId); StyleText styleText = source.GetStyleText(sceneTextObject.StyleId); string text = source.GetText(sceneTextObject.TextId); target.AddText(target.AddPoint(scenePoint.X, scenePoint.Y), styleText.Layer, styleText.MinZoom, styleText.MaxZoom, styleText.Size, text, styleText.Color, styleText.HaloColor, styleText.HaloRadius, styleText.Font); } } // loop until there are no more candidates. int totalLines = lines.Count; float latestProgress = 0; while (lines.Count > 0) { var line = lines.First(); lines.Remove(line.Key); // report progress. float progress = (float)System.Math.Round((((double)(totalLines - lines.Count) / (double)totalLines) * 100)); if (progress != latestProgress) { OsmSharp.Logging.Log.TraceEvent("SceneSerializer", OsmSharp.Logging.TraceEventType.Information, "Merging lines ({1}/{2})... {0}%", progress, totalLines - lines.Count, totalLines); latestProgress = progress; } // copy the coordinates to lists. double[] x = line.Key.X.Clone() as double[]; double[] y = line.Key.Y.Clone() as double[]; // find a matching line. int mergeCount = 1; Scene2D.ScenePoints found; MatchPosition foundPosition = this.FindMatch(lines, x, y, line.Value, out found); while (found != null) { // TODO: keep expanding and duplicating until not possible anymore. // remove the found line. lines.Remove(found); // add the line. int lengthBefore = x.Length; Array.Resize(ref x, x.Length + found.X.Length - 1); Array.Resize(ref y, y.Length + found.Y.Length - 1); switch (foundPosition) { case MatchPosition.FirstFirst: found.X.InsertToReverse(1, x, 0, found.X.Length - 1); found.Y.InsertToReverse(1, y, 0, found.Y.Length - 1); break; case MatchPosition.FirstLast: found.X.InsertTo(0, x, 0, found.X.Length - 1); found.Y.InsertTo(0, y, 0, found.Y.Length - 1); break; case MatchPosition.LastFirst: found.X.CopyTo(x, lengthBefore - 1); found.Y.CopyTo(y, lengthBefore - 1); break; case MatchPosition.LastLast: found.X.CopyToReverse(x, lengthBefore - 1); found.Y.CopyToReverse(y, lengthBefore - 1); break; } // select a new line. foundPosition = this.FindMatch(lines, x, y, line.Value, out found); mergeCount++; } // add the new points. uint? pointsId = target.AddPoints(x, y); // add points again with appropriate styles. if (pointsId.HasValue) { foreach (var style in line.Value) { var scene2DStyleLine = (style as Scene2DStyleLine); if (scene2DStyleLine != null) { StyleLine styleLine = source.GetStyleLine(scene2DStyleLine.StyleLineId); target.AddStyleLine(pointsId.Value, styleLine.Layer, styleLine.MinZoom, styleLine.MaxZoom, styleLine.Color, styleLine.Width, styleLine.LineJoin, styleLine.Dashes); continue; } var scene2DStyleLineText = (style as Scene2DStyleLineText); if (scene2DStyleLineText != null) { StyleText styleText = source.GetStyleLineText(scene2DStyleLineText.StyleLineTextId); string text = source.GetText(scene2DStyleLineText.TextId); target.AddStyleLineText(pointsId.Value, styleText.Layer, styleText.MinZoom, styleText.MaxZoom, styleText.Color, styleText.Size, text, styleText.Font, styleText.HaloColor, styleText.HaloRadius); continue; } } } } }
/// <summary> /// Try and find matching lines. /// </summary> /// <param name="lines"></param> /// <param name="points"></param> /// <returns></returns> private MatchPosition FindMatch(ILocatedObjectIndex<PointF2D, Scene2D.ScenePoints> linesIndex, Dictionary<Scene2D.ScenePoints, Scene2DStylesSet> lines, double[] x, double[] y, Scene2DStylesSet style, float epsilon, out Scene2D.ScenePoints found) { // build box. var box = new BoxF2D(x, y); box = box.ResizeWith(epsilon * 1.1); // get all geometries in this box. var potentialMatches = linesIndex.GetInside(box); // find a match in the potential matches list. PointF2D first = new PointF2D(x[0], y[0]); PointF2D last = new PointF2D(x[x.Length - 1], y[y.Length - 1]); MatchPosition position = MatchPosition.None; found = null; foreach (var line in potentialMatches) { // check first. PointF2D potentialFirst = new PointF2D(line.X[0], line.Y[0]); PointF2D potentialLast = new PointF2D(line.X[line.X.Length - 1], line.Y[line.Y.Length - 1]); if (first.Distance(potentialFirst) < epsilon) { found = line; position = MatchPosition.FirstFirst; } else if (last.Distance(potentialFirst) < epsilon) { found = line; position = MatchPosition.LastFirst; } else if (first.Distance(potentialLast) < epsilon) { found = line; position = MatchPosition.FirstLast; } else if (last.Distance(potentialLast) < epsilon) { found = line; position = MatchPosition.LastLast; } Scene2DStylesSet styleValue; if (position != MatchPosition.None && lines.TryGetValue(line, out styleValue) && styleValue.Equals(style)) { break; } else { position = MatchPosition.None; found = null; } } return position; }
/// <summary> /// Try and find matching lines. /// </summary> /// <param name="lines"></param> /// <param name="points"></param> /// <returns></returns> private MatchPosition FindMatch(Dictionary<Scene2D.ScenePoints, Scene2DStylesSet> lines, double[] x, double[] y, Scene2DStylesSet style, out Scene2D.ScenePoints found) { PointF2D first = new PointF2D(x[0], y[0]); PointF2D last = new PointF2D(x[x.Length - 1], y[y.Length - 1]); MatchPosition position = MatchPosition.None; found = null; foreach (var line in lines) { if (line.Value.Equals(style)) { // check first. PointF2D potentialFirst = new PointF2D(line.Key.X[0], line.Key.Y[0]); if (first.Distance(potentialFirst) < _epsilon) { found = line.Key; position = MatchPosition.FirstFirst; break; } if (last.Distance(potentialFirst) < _epsilon) { found = line.Key; position = MatchPosition.LastFirst; break; } PointF2D potentialLast = new PointF2D(line.Key.X[line.Key.X.Length - 1], line.Key.Y[line.Key.Y.Length - 1]); if (first.Distance(potentialLast) < _epsilon) { found = line.Key; position = MatchPosition.FirstLast; break; } if (last.Distance(potentialLast) < _epsilon) { found = line.Key; position = MatchPosition.LastLast; break; } } } return position; }
/// <summary> /// Serializes the given scene. /// </summary> /// <param name="stream"></param> /// <param name="scene"></param> /// <param name="compress"></param> public static void Serialize(Stream stream, TagsCollectionBase metaTags, Scene2D scene, bool compress) { RuntimeTypeModel typeModel = SceneSerializer.BuildRuntimeTypeModel(); // [MetaIndexLenght:4][Metadata][SeneIndexLength:4][SceneIndex][SceneLengths:4*zoomFactors.length][Scenes] // MetaIndexLenght: int The lenght of the meta index. // Metadata: a number of serialized tags. // SceneIndexLength: int The length of the sceneindex in bytes. // SceneIndex: the serialized scene index. // SceneLengths: int[] The lengths of the scenes per zoom level as in the zoomfactors array. // Scenes: The serialized scenes themselves. // serialize meta tags. (new TagsCollectionSerializer()).SerializeWithSize(metaTags, stream); // index index. SceneIndex sceneIndex = new SceneIndex(); sceneIndex.LineStyles = scene.GetStyleLines(); sceneIndex.PointStyles = scene.GetStylePoints(); sceneIndex.PolygonStyles = scene.GetStylePolygons(); sceneIndex.TextStyles = scene.GetStyleTexts(); sceneIndex.ZoomRanges = scene.GetZoomRanges(); sceneIndex.ZoomFactors = scene.GetZoomFactors(); sceneIndex.IconImage = scene.GetImages(); // write SceneIndex long positionAfterMeta = stream.Position; stream.Seek(positionAfterMeta + 4, SeekOrigin.Begin); long indexStart = stream.Position; typeModel.Serialize(stream, sceneIndex); // write SeneIndexLength int indexSize = (int)(stream.Position - indexStart); stream.Seek(positionAfterMeta + 0, SeekOrigin.Begin); stream.Write(BitConverter.GetBytes(indexSize), 0, 4); // write Scenes. stream.Seek(positionAfterMeta + 4 + indexSize + 4 * sceneIndex.ZoomFactors.Length, SeekOrigin.Begin); // index into r-trees and serialize. int[] lengths = new int[sceneIndex.ZoomFactors.Length]; for (int idx = 0; idx < lengths.Length; idx++) { long position = stream.Position; Dictionary<uint, SceneObject> sceneAtZoom = scene.GetObjectsAt(idx); RTreeMemoryIndex<SceneObject> memoryIndex = new RTreeMemoryIndex<SceneObject>(50, 100); float latestProgress = 0; int sceneObjectIdx = 0; foreach (KeyValuePair<uint, SceneObject> sceneObjectPair in sceneAtZoom) { // loop over all primitives in order. SceneObject sceneObject = sceneObjectPair.Value; uint id = sceneObjectPair.Key; switch (sceneObject.Enum) { case SceneObjectType.IconObject: case SceneObjectType.PointObject: case SceneObjectType.TextObject: OsmSharp.UI.Renderer.Scene.Scene2D.ScenePoint geo = scene.GetPoint(sceneObject.GeoId); PointF2D point = new PointF2D(geo.X, geo.Y); memoryIndex.Add(new BoxF2D(point), sceneObject); break; case SceneObjectType.LineObject: case SceneObjectType.LineTextObject: case SceneObjectType.PolygonObject: OsmSharp.UI.Renderer.Scene.Scene2D.ScenePoints geos = scene.GetPoints(sceneObject.GeoId); memoryIndex.Add(new BoxF2D(geos.X, geos.Y), sceneObject); break; } float progress = (float)System.Math.Round((((double)sceneObjectIdx / (double)sceneAtZoom.Count) * 100)); if (progress != latestProgress) { OsmSharp.Logging.Log.TraceEvent("SceneSerializer", OsmSharp.Logging.TraceEventType.Information, "Indexing scene objects at zoom {1} ({2}/{3})... {0}%", progress, sceneIndex.ZoomFactors[idx], sceneObjectIdx, sceneAtZoom.Count); latestProgress = progress; } sceneObjectIdx++; } // serialize the r-tree. OsmSharp.Logging.Log.TraceEvent("SceneSerializer", OsmSharp.Logging.TraceEventType.Information, "Serializing RTRee..."); SceneObjectRTreeSerializer memoryIndexSerializer = new SceneObjectRTreeSerializer( scene, compress, idx, SceneSerializer.CalculateScaleFactor(sceneIndex.ZoomFactors[idx])); memoryIndexSerializer.Serialize(new LimitedStream(stream), memoryIndex); lengths[idx] = (int)(stream.Position - position); } // write SceneLengths long end = stream.Position; stream.Seek(positionAfterMeta + 4 + indexSize, SeekOrigin.Begin); for (int idx = 0; idx < lengths.Length; idx++) { stream.Write(BitConverter.GetBytes(lengths[idx]), 0, 4); } stream.Seek(end, SeekOrigin.Begin); }
public float widthOrHeight = 1f; // by height #endregion Fields #region Methods protected void Awake() { if (isMain) main = this; }