### Kotlin HttpServer Initialization and Start Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html Initializes a Netty-based HTTP server in Kotlin, setting up worker groups, the server bootstrap, and binding to a specified port. It includes functionality to start the server and optionally wait for it to close. ```kotlin package org.wasabi.http import java.util.concurrent.Executors import java.net.InetSocketAddress import org.wasabi.app.AppConfiguration import io.netty.bootstrap.ServerBootstrap import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.nio.NioServerSocketChannel import org.wasabi.app.AppServer public class HttpServer(private val appServer: AppServer) { val bootstrap: ServerBootstrap val primaryGroup: NioEventLoopGroup val workerGroup: NioEventLoopGroup init { // Define worker groups primaryGroup = NioEventLoopGroup() workerGroup = NioEventLoopGroup() // Initialize bootstrap of server bootstrap = ServerBootstrap() bootstrap.group(primaryGroup, workerGroup) bootstrap.channel(javaClass()) bootstrap.childHandler(NettyPipelineInitializer(appServer)) } public fun start(wait: Boolean = true) { val channel = bootstrap.bind(appServer.configuration.port)?.sync()?.channel() if (wait) { channel?.closeFuture()?.sync() } } public fun stop() { // Shutdown all event loops primaryGroup.shutdownGracefully() workerGroup.shutdownGracefully() // Wait till all threads are terminated primaryGroup.terminationFuture().sync() workerGroup.terminationFuture().sync() } } ``` -------------------------------- ### Objective-C AppDelegate Example Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html A basic Objective-C code snippet for an AppDelegate class, including a multi-line comment and a method stub for `application:didFinishLaunchingWithOptions:`. It demonstrates Objective-C syntax for imports, class implementations, and Objective-C character arrays. Dependencies include Test/Test.h. ```objectivec /* This is a longer comment That spans two lines */ #import @implementation YourAppDelegate // This is a one-line comment - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ char myString[] = "This is a C character array"; int test = 5; return YES; } ``` -------------------------------- ### C ZMQ Thread Example Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html Demonstrates a C code snippet for creating and managing a ZeroMQ (zmq) thread using POSIX threads (pthread) and semaphores. It includes functions for initializing the thread context and handling various ZeroMQ commands within the thread. Dependencies include zmq.h, pthread.h, semaphore.h, time.h, stdio.h, fcntl.h, and malloc.h. ```c /* C demo code */ #include #include #include #include #include #include #include typedef struct { void* arg_socket; zmq_msg_t* arg_msg; char* arg_string; unsigned long arg_len; int arg_int, arg_command; int signal_fd; int pad; void* context; sem_t sem; } acl_zmq_context; #define p(X) (context->arg_##X) void* zmq_thread(void* context_pointer) { acl_zmq_context* context = (acl_zmq_context*)context_pointer; char ok = 'K', err = 'X'; int res; while (1) { while ((res = sem_wait(&context->sem)) == EINTR); if (res) { write(context->signal_fd, &err, 1); goto cleanup; } switch(p(command)) { case 0: goto cleanup; case 1: p(socket) = zmq_socket(context->context, p(int)); break; case 2: p(int) = zmq_close(p(socket)); break; case 3: p(int) = zmq_bind(p(socket), p(string)); break; case 4: p(int) = zmq_connect(p(socket), p(string)); break; case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &p(len)); break; case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break; case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break; case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break; case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break; } p(command) = errno; write(context->signal_fd, &ok, 1); } cleanup: close(context->signal_fd); free(context_pointer); return 0; } void* zmq_thread_init(void* zmq_context, int signal_fd) { acl_zmq_context* context = malloc(sizeof(acl_zmq_context)); pthread_t thread; context->context = zmq_context; context->signal_fd = signal_fd; sem_init(&context->sem, 1, 0); pthread_create(&thread, 0, &zmq_thread, context); pthread_detach(thread); return context; } ``` -------------------------------- ### C++ Class Template and String Literals Example Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html Illustrates C++ features including class templates, namespaces, enums, unicode string literals, raw string literals, and method definitions. It showcases a generic class `Class` with a template, a const member, and methods, demonstrating inheritance and template specialization. Dependencies include mystuff/util.h. ```cpp #include #include "mystuff/util.h" namespace { enum Enum { VAL1, VAL2, VAL3 }; char32_t unicode_string = U"\U0010FFFF"; string raw_string = R"delim(anything you want)delim"; int Helper(const MyType& param) { return 0; } } // namespace class ForwardDec; template class Class : public BaseClass { const MyType member_; public: const MyType& Method() const { return member_; } void Method2(MyType* value); } template void Class::Method2(MyType* value) { std::out << 1 >> method(); value->Method3(member_); member_ = value; } ``` -------------------------------- ### Scala List Filtering Example Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html A Scala object `FilterTest` demonstrating a recursive function `filter` that takes a list of integers and a threshold, returning a new list containing elements less than the threshold. It utilizes inner helper functions for processing. This example highlights functional programming concepts in Scala. ```scala object FilterTest extends App { def filter(xs: List[Int], threshold: Int) = { def process(ys: List[Int]): List[Int] = if (ys.isEmpty) ys else if (ys.head < threshold) ys.head :: process(ys.tail) else process(ys.tail) process(xs) } println(filter(List(1, 9, 2, 8, 3, 7, 4), 5)) } ``` -------------------------------- ### CodeMirror Editor Initialization for Multiple Languages Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html Initializes CodeMirror editors for various programming languages using `CodeMirror.fromTextArea`. Each editor is configured with line numbers, bracket matching, and a specific mode for syntax highlighting. ```javascript var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-csrc" }); var cppEditor = CodeMirror.fromTextArea(document.getElementById("cpp-code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-c++src" }); var javaEditor = CodeMirror.fromTextArea(document.getElementById("java-code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-java" }); var objectivecEditor = CodeMirror.fromTextArea(document.getElementById("objectivec-code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-objectivec" }); var scalaEditor = CodeMirror.fromTextArea(document.getElementById("scala-code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-scala" }); var kotlinEditor = CodeMirror.fromTextArea(document.getElementById("kotlin-code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-kotlin" }); var ceylonEditor = CodeMirror.fromTextArea(document.getElementById("ceylon-code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-ceylon" }); ``` -------------------------------- ### Java Generic Enum and Class Example Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html Provides a Java code example featuring a generic enum and a generic class `Class` that implements an interface. It includes static final members, inner classes, and method implementations, demonstrating generic type parameters and method overriding. Dependencies include com.demo.util.MyType and com.demo.util.MyInterface. ```java import com.demo.util.MyType; import com.demo.util.MyInterface; public enum Enum { VAL1, VAL2, VAL3 } public class Class implements MyInterface { public static final MyType member; private class InnerClass { public int zero() { return 0; } } @Override public MyType method() { return member; } public void method2(MyType value) { method(); value.method3(); member = value; } } ``` -------------------------------- ### Ceylon Stream Loop Functionality Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html Defines a 'loop' function in Ceylon that generates a stream by repeatedly applying a function to a starting element until a 'finished' condition is met. This can result in finite or infinite streams. ```ceylon "Produces the [[stream|Iterable]] that results from repeated application of the given [[function|next]] to the given [[first]] element of the stream, until the function first returns [[finished]]. If the given function never returns `finished`, the resulting stream is infinite. For example: loop(0)(2.plus).takeWhile(10.largerThan) produces the stream `{ 0, 2, 4, 6, 8 }`." tagged("Streams") shared { Element+ } loop( "The first element of the resulting stream." Element first )( "The function that produces the next element of the stream, given the current element. The function may return [[finished]] to indicate the end of the stream." Element|Finished next(Element element) ) => let (start = first) object satisfies { Element+ } { first => start; empty => false; function nextElement(Element element) => next(element); iterator() => object satisfies Iterator { variable Element|Finished current = start; shared actual Element|Finished next() { if (!is Finished result = current) { current = nextElement(result); return result; } else { return finished; } } }; }; ``` -------------------------------- ### Scala Collection API Example Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/scala.html This snippet demonstrates the Scala collection API, specifically the TraversableLike trait. It defines common behaviors for Scala collections, including methods like 'foreach' and 'newBuilder'. The description explains the concepts of strictness and orderedness in collections. ```scala /* __ *\ ** ___ ________ ___ / / ___ Scala API ** ** /_/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** ** __\ \/ /_/ _ |/ /__/ __ | http://scala-lang.org/ ** ** /____\___/ / |\____/_/ | | ** ** |/ ** \*/ package scala.collection import generic._ import mutable.Builder, ListBuffer import annotation.{tailrec, migration, bridge} import annotation.unchecked.uncheckedVariance => uV } import parallel.ParIterable /** A template trait for traversable collections of type `Traversable[A]`. * * $traversableInfo * @define mutability * @define traversableInfo * This is a base trait of all kinds of $mutability Scala collections. It * implements the behavior common to all collections, in terms of a method * `foreach` with signature: * {{{ * def foreach[U](f: Elem => U): Unit * }}} * Collection classes mixing in this trait provide a concrete * `foreach` method which traverses all the * elements contained in the collection, applying a given function to each. * They also need to provide a method `newBuilder` * which creates a builder for collections of the same kind. * * A traversable class might or might not have two properties: strictness * and orderedness. Neither is represented as a type. * * The instances of a strict collection class have all their elements computed before they can be used as values. By contrast, instances of a non-strict collection class may defer computation of some of their elements until after the instance is available as a value. A typical example of a non-strict collection class is a `scala.collection.immutable.Stream`. A more general class of examples are `TraversableViews`. * * If a collection is an instance of an ordered collection class, traversing its elements with `foreach` will always visit elements in the same order, even for different runs of the program. If the class is not ordered, `foreach` can visit elements in different orders for different runs (but it will keep the same order in the same run).' * A typical example of a collection class which is not ordered is a `HashMap` of objects. The traversal order for hash maps will depend on the hash codes of its elements, and these hash codes might differ from one run to the next. By contrast, a `LinkedHashMap` is ordered because it's `foreach` method visits elements in the order they were inserted into the `HashMap`. * * @author Martin Odersky * @version 2.8 * @since 2.8 * @tparam A the element type of the collection * @tparam Repr the type of the actual collection containing the elements. * * @define Coll Traversable * @define coll traversable collection */ trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] with FilterMonadic[A, Repr] with TraversableOnce[A] with GenTraversableLike[A, Repr] with Parallelizable[A, ParIterable[A]] { self => import Traversable.breaks._ /** The type implementing this traversable */ protected type Self = Repr /** The collection of type $coll underlying this `TraversableLike` object. * By default this is implemented as the `TraversableLike` object itself, * but this can be overridden. */ def repr: Repr = this.asInstanceOf[Repr] /** The underlying collection seen as an instance of `$Coll`. * By default this is implemented as the current collection object itself, * but this can be overridden. */ protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]] /** A conversion from collections of type `Repr` to `$Coll` objects. * By default this is implemented as just a cast, but this can be overridden. */ protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]] /** Creates a new builder for this collection type. */ protected[this] def newBuilder: Builder[A, Repr] protected[this] def parCombiner = ParIterable.newCombiner[A] /** Applies a function `f` to all elements of this $coll. * * Note: this method underlies the implementation of most other bulk operations. * It's important to implement this method in an efficient way. * * * @param f the function that is applied for its side-effect to every element. * The result of function `f` is discarded. * * @tparam U the type parameter describing the result of function `f`. * This result will always be ignored. Typically `U` is `Unit`, * but this is not necessary. * * @usecase def foreach(f: A => Unit): Unit */ def foreach[U](f: A => U): Unit /** Test ``` -------------------------------- ### CodeMirror Default Keymap and Autocomplete Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/index.html Configures the default CodeMirror keymap to include an autocomplete shortcut. It checks if the operating system is Mac and sets the shortcut to 'Cmd-Space' or 'Ctrl-Space' accordingly. ```javascript var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault; CodeMirror.keyMap.default[(mac ? "Cmd" : "Ctrl") + "-Space"] = "autocomplete"; ``` -------------------------------- ### Animate Shapes and Camera in WorldWind Android Source: https://context7.com/nasaworldwind/worldwindandroid/llms.txt Provides examples for creating animation loops using Handlers to update placemark positions in circular motion and to smoothly animate the camera's position and heading. It demonstrates starting and stopping animations and using ValueAnimator for smooth transitions. ```java // Handler for periodic updates Handler animationHandler = new Handler(); // Store renderables to animate List placemarks = new ArrayList<>(); // Animation loop Runnable animationRunnable = new Runnable() { private float angle = 0; @Override public void run() { // Update placemark positions for (int i = 0; i < placemarks.size(); i++) { Placemark pm = placemarks.get(i); Position pos = pm.getPosition(); // Calculate new position (circular motion) double newLat = 34.2 + Math.sin(angle + i) * 0.1; double newLon = -119.2 + Math.cos(angle + i) * 0.1; pm.setPosition(Position.fromDegrees(newLat, newLon, pos.altitude)); } // Animate camera Navigator nav = wwd.getNavigator(); nav.setHeading((nav.getHeading() + 1) % 360); // Request redraw to display changes wwd.requestRedraw(); // Increment angle angle += 0.05f; // Schedule next frame (20 FPS) animationHandler.postDelayed(this, 50); } }; // Start animation animationHandler.post(animationRunnable); // Stop animation animationHandler.removeCallbacks(animationRunnable); // Smooth camera animation using Navigator Navigator nav = wwd.getNavigator(); ValueAnimator animator = ValueAnimator.ofFloat(0, 1); animator.setDuration(2000); // 2 seconds animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { private double startLat = nav.getLatitude(); private double startLon = nav.getLongitude(); private double endLat = 37.7749; private double endLon = -122.4194; @Override public void onAnimationUpdate(ValueAnimator animation) { float fraction = animation.getAnimatedFraction(); nav.setLatitude(startLat + (endLat - startLat) * fraction); nav.setLongitude(startLon + (endLon - startLon) * fraction); wwd.requestRedraw(); } }); animator.start(); ``` -------------------------------- ### Getting the First Element Optionally (HeadOption) in Scala Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/scala.html Returns an `Option` containing the first element of the collection if it is non-empty, otherwise returns `None`. This is a safe way to access the first element, avoiding exceptions for empty collections. It is order-dependent. ```Scala /** * Optionally selects the first element. * $orderDependent * @return the first element of this $coll if it is nonempty, `None` if it is empty. */ def headOption: Option[A] = if (isEmpty) None else Some(head) ``` -------------------------------- ### Control Camera and Navigator (Java) Source: https://context7.com/nasaworldwind/worldwindandroid/llms.txt Provides examples for controlling the camera's position and orientation in WorldWind Android using Navigator, Camera, and LookAt models. It covers direct position setting, using Camera objects, LookAt configurations, and listening for navigator events. ```java Navigator navigator = wwd.getNavigator(); // Direct position control navigator.setLatitude(34.2) .setLongitude(-119.2) .setAltitude(10000) .setHeading(45) .setTilt(70) .setRoll(0); // Camera model (direct eye position and orientation) Camera camera = new Camera( 37.7749, // latitude -122.4194, // longitude 1000, // altitude (meters) WorldWind.ABSOLUTE, 45, // heading (degrees) 60, // tilt (degrees) 0 // roll (degrees) ); navigator.setAsCamera(wwd.getGlobe(), camera); // LookAt model (look at a position from a distance) LookAt lookAt = new LookAt(); lookAt.set( 34.2, // latitude to look at -119.2, // longitude to look at 0, // altitude to look at WorldWind.ABSOLUTE, 50000, // range (distance from look-at point) 0, // heading 70, // tilt 0 // roll ); navigator.setAsLookAt(wwd.getGlobe(), lookAt); // Retrieve current camera state Camera currentCamera = navigator.getAsCamera(wwd.getGlobe(), new Camera()); // Listen for navigator changes wwd.addNavigatorListener(new NavigatorListener() { @Override public void onNavigatorEvent(WorldWindow wwd, NavigatorEvent event) { if (event.isStoppedMoving()) { // Navigator has stopped moving Camera camera = wwd.getNavigator().getAsCamera(wwd.getGlobe(), new Camera()); Log.i("Position", String.format("Lat: %.4f, Lon: %.4f, Alt: %.0f", camera.latitude, camera.longitude, camera.altitude)); } } }); // Set delay before "stopped moving" event fires wwd.setNavigatorStoppedDelay(500, TimeUnit.MILLISECONDS); // Calculate distance to view entire globe double distance = wwd.distanceToViewGlobeExtents(); navigator.setAltitude(distance * 1.1); ``` -------------------------------- ### Add Placemarks to RenderableLayer in Java Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/placemarks_tutorial.html This Java code snippet demonstrates creating a WorldWindow, adding a RenderableLayer, and then populating it with four different Placemarks. It shows how to create basic color-coded placemarks and image-based placemarks with custom attributes, including image scaling, leader lines, labels, and bitmap sources. Finally, it adds these placemarks to the layer and sets the viewer's perspective. ```java package gov.nasa.worldwindx); import gov.nasa.worldwind.geom.Position; import gov.nasa.worldwind.geom.LookAt; import gov.nasa.worldwind.geom.Offset; import gov.nasa.worldwind.layers.RenderableLayer; import gov.nasa.worldwind.render.Placemark; import gov.nasa.worldwind.render.PlacemarkAttributes; import gov.nasa.worldwind.render.ImageSource; import gov.nasa.worldwind.WorldWindow; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.awt.Color; public class PlacemarksFragment extends BasicGlobeFragment { /** * Creates a new WorldWindow with a RenderableLayer populated with four Placemarks. */ @Override public WorldWindow createWorldWindow() { // Let the super class (BasicGlobeFragment) do the creation WorldWindow wwd = super.createWorldWindow(); // Create a RenderableLayer for placemarks and add it to the WorldWindow RenderableLayer placemarksLayer = new RenderableLayer("Placemarks"); wwd.getLayers().addLayer(placemarksLayer); ////////////////////////////////////// // Second, create some placemarks... ///////////////////////////////////// // Create a simple placemark at downtown Ventura, CA. This placemark is a 20x20 cyan square centered on the // geographic position. This placemark demonstrates the creation with a convenient factory method. Placemark ventura = Placemark.createWithColorAndSize(Position.fromDegrees(34.281, -119.293, 0), new Color(0, 1, 1, 1), 20); // Create an image-based placemark of an aircraft above the ground with a leader-line to the surface. // This placemark demonstrates creation via a constructor and a convenient PlacemarkAttributes factory method. // The image is scaled to 1.5 times its original size. Placemark airplane = new Placemark( Position.fromDegrees(34.260, -119.2, 5000), PlacemarkAttributes.createWithImageAndLeader(ImageSource.fromResource(R.drawable.aircraft_fixwing)).setImageScale(1.5)); // Create an image-based placemark with a label at Oxnard Airport, CA. This placemark demonstrates creation // with a constructor and a convenient PlacemarkAttributes factory method. The image is scaled to 2x // its original size, with the bottom center of the image anchored at the geographic position. Placemark airport = new Placemark( Position.fromDegrees(34.200, -119.208, 0), PlacemarkAttributes.createWithImage(ImageSource.fromResource(R.drawable.airport_terminal)).setImageOffset(Offset.bottomCenter()).setImageScale(2), "Oxnard Airport"); // Create an image-based placemark from a bitmap. This placemark demonstrates creation with a // constructor and a convenient PlacemarkAttributes factory method. First, a 64x64 bitmap is loaded // and then it is passed into the placemark attributes. The the bottom center of the image anchored // at the geographic position. Bitmap bitmap = BitmapFactory.decodeResource(getWorldWindow().getResources(), R.drawable.ehipcc); Placemark wildfire = new Placemark( Position.fromDegrees(34.300, -119.25, 0), PlacemarkAttributes.createWithImage(ImageSource.fromBitmap(bitmap)).setImageOffset(Offset.bottomCenter())); //////////////////////////////////////////////////// // Third, add the placemarks to the renderable layer //////////////////////////////////////////////////// placemarksLayer.addRenderable(ventura); placemarksLayer.addRenderable(airport); placemarksLayer.addRenderable(airplane); placemarksLayer.addRenderable(wildfire); // And finally, for this demo, position the viewer to look at the airport placemark // from a tilted perspective when this Android activity is created. Position pos = airport.getPosition(); LookAt lookAt = new LookAt().set(pos.latitude, pos.longitude, pos.altitude, WorldWind.ABSOLUTE, 1e5 /*range*/, 0 /*heading*/, 80 /*tilt*/, 0 /*roll*/); wwd.getNavigator().setAsLookAt(wwd.getGlobe(), lookAt); return wwd; } } ``` -------------------------------- ### Create and Configure WorldWindow in Android Fragment (Java) Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/basic_globe_tutorial.html This Java code demonstrates how to create a WorldWindow (a GLSurfaceView) within an Android Fragment. It initializes the WorldWindow, adds background and landmass layers, and sets up the elevation model. The WorldWindow is then added to the Fragment's layout. ```Java package gov.nasa.worldwindx; import androidx.annotation.Nullable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.fragment.app.Fragment; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.geom.Camera; import gov.nasa.worldwind.layer.BackgroundLayer; import gov.nasa.worldwind.layer.BlueMarbleLandsatLayer; import gov.nasa.worldwind.render.AbstractRetrievalPostLayer; import gov.nasa.worldwind.globes.BasicElevationCoverage; public class BasicGlobeFragment extends Fragment { private WorldWindow wwd; public BasicGlobeFragment() { } /** * Creates a new WorldWindow (GLSurfaceView) object. */ public WorldWindow createWorldWindow() { // Create the WorldWindow (a GLSurfaceView) which displays the globe. this.wwd = new WorldWindow(getContext()); // Setup the WorldWindow's layers. this.wwd.getLayers().addLayer(new BackgroundLayer()); this.wwd.getLayers().addLayer(new BlueMarbleLandsatLayer()); // Setup the WorldWindow's elevation coverages. this.wwd.getGlobe().getElevationModel().addCoverage(new BasicElevationCoverage()); return this.wwd; } /** * Gets the WorldWindow (GLSurfaceView) object. */ public WorldWindow getWorldWindow() { return this.wwd; } /** * Adds the WorldWindow to this Fragment's layout. */ @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_globe, container, false); FrameLayout globeLayout = (FrameLayout) rootView.findViewById(R.id.globe); // Add the WorldWindow view object to the layout that was reserved for the globe. globeLayout.addView(this.createWorldWindow()); return rootView; } /** * Resumes the WorldWindow's rendering thread */ @Override public void onResume() { super.onResume(); this.wwd.onResume(); // resumes a paused rendering thread } /** * Pauses the WorldWindow's rendering thread */ @Override public void onPause() { super.onPause(); this.wwd.onPause(); // pauses the rendering thread } } ``` -------------------------------- ### Display GeoPackage Layer with LayerFactory in Java Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/geopackage_tutorial.html This Java code snippet demonstrates how to create and display an OGC GeoPackage layer using WorldWind's LayerFactory. It handles unpacking the GeoPackage asset, asynchronously creating the layer, and adding it to the WorldWindow, including logic for success and failure callbacks. Dependencies include Android context, WorldWind libraries, and tutorial utilities. ```java package gov.nasa.worldwindx); import android.util.Log; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.layers.Layer; import gov.nasa.worldwind.ogc.wms.WMSLayer; import gov.nasa.worldwind.ogc.wms.WMSImageDescription; import gov.nasa.worldwind.layers.LayerFactory; import gov.nasa.worldwind.globes.BasicGlobeFragment; import java.io.File; public class GeoPackageFragment extends BasicGlobeFragment { /** * Creates a new WorldWindow (GLSurfaceView) object with a GeoPackage Layer * * @return The WorldWindow object containing the globe. */ @Override public WorldWindow createWorldWindow() { // Let the super class (BasicGlobeFragment) do the creation WorldWindow wwd = super.createWorldWindow(); // Unpack the tutorial GeoPackage asset to the Android application cache. // GeoPackage relies on the Android SQLite library which operates only on files in the local Android filesystem. File geoPackageFile = TutorialUtil.unpackAsset(this.getContext(), "geopackage_tutorial.gpkg"); // Create a layer factory, WorldWind's general component for creating layers // from complex data sources. LayerFactory layerFactory = new LayerFactory(); // Create an OGC GeoPackage layer to display a high resolution monochromatic image of Naval Air Station Oceana // in Virginia Beach, VA. layerFactory.createFromGeoPackage( geoPackageFile.getPath(), // file path on the local Android filesystem new LayerFactory.Callback() { @Override public void creationSucceeded(LayerFactory factory, Layer layer) { // Add the finished GeoPackage layer to the WorldWindow. getWorldWindow().getLayers().addLayer(layer); // Place the viewer directly over the GeoPackage image. getWorldWindow().getNavigator().setLatitude(36.8139677556754); getWorldWindow().getNavigator().setLongitude(-76.03260320181615); getWorldWindow().getNavigator().setAltitude(20e3); Log.i("gov.nasa.worldwind", "GeoPackage layer creation succeeded"); } @Override public void creationFailed(LayerFactory factory, Layer layer, Throwable ex) { // Something went wrong reading the GeoPackage. Log.e("gov.nasa.worldwind", "GeoPackage layer creation failed", ex); } } ); return wwd; } } ``` -------------------------------- ### Getting the Last Element in Scala Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/scala.html Returns the last element of the collection. This operation will throw a `NoSuchElementException` if the collection is empty. It is order-dependent. ```Scala /** * Selects the last element. * $orderDependent * @return The last element of this $coll. * @throws NoSuchElementException If the $coll is empty. */ def last: A = { var lst = head for (x <- this) lst = x lst } ``` -------------------------------- ### Show Tessellation Layer in Java Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/show_tessellation_tutorial.html The `ShowTessellationFragment` class extends `BasicGlobeFragment` and overrides `createWorldWindow` to add a `ShowTessellationLayer`. This layer visualizes the globe's tessellation geometry. It depends on the WorldWind library and takes no explicit input, outputting a configured `WorldWindow` instance. ```java package gov.nasa.worldwindx; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.layers.ShowTessellationLayer; public class ShowTessellationFragment extends BasicGlobeFragment { /** * Creates a new WorldWindow with a additional tessellation layer. */ @Override public WorldWindow createWorldWindow() { // Let the super class (BasicGlobeFragment) do the creation WorldWindow wwd = super.createWorldWindow(); // Create a layer that displays the globe's tessellation geometry. ShowTessellationLayer layer = new ShowTessellationLayer(); wwd.getLayers().addLayer(layer); return wwd; } } ``` -------------------------------- ### Getting the First Element (Head) in Scala Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/scala.html Returns the first element of the collection. This operation will throw a `NoSuchElementException` if the collection is empty. It is order-dependent. ```Scala /** * Selects the first element of this $coll. * $orderDependent * @return the first element of this $coll. * @throws `NoSuchElementException` if the $coll is empty. */ def head: A = { var result: () => A = () => throw new NoSuchElementException breakable { for (x <- this) { result = () => x break } } result() } ``` -------------------------------- ### Create WorldWindow with Placemarks and Custom Controller (Java) Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/placemarks_picking_tutorial.html This code snippet demonstrates the creation of a WorldWindow in Android using Java. It initializes a RenderableLayer, adds several placemarks (airports and an aircraft) with custom scaling and highlight attributes, and sets a custom PickNavigateController to handle touch events for picking and navigation. The viewer's position is then set using a LookAt object. ```java package gov.nasa.worldwindx; ... public class PlacemarksPickingFragment extends BasicGlobeFragment { private static final double NORMAL_IMAGE_SCALE = 3.0; private static final double HIGHLIGHTED_IMAGE_SCALE = 4.0; /** * Creates a new WorldWindow (GLSurfaceView) object with a WMS Layer * * @return The WorldWindow object containing the globe. */ @Override public WorldWindow createWorldWindow() { // Let the super class (BasicGlobeFragment) do the creation WorldWindow wwd = super.createWorldWindow(); // Override the WorldWindow's built-in navigation behavior by adding picking support. wwd.setWorldWindowController(new PickNavigateController()); // Add a layer for placemarks to the WorldWindow RenderableLayer layer = new RenderableLayer("Placemarks"); wwd.getLayers().addLayer(layer); // Create a few placemarks with highlight attributes and add them to the layer layer.addRenderable(createAirportPlacemark(Position.fromDegrees(34.2000, -119.2070, 0), "Oxnard Airport")); layer.addRenderable(createAirportPlacemark(Position.fromDegrees(34.2138, -119.0944, 0), "Camarillo Airport")); layer.addRenderable(createAirportPlacemark(Position.fromDegrees(34.1193, -119.1196, 0), "Pt Mugu Naval Air Station")); layer.addRenderable(createAircraftPlacemark(Position.fromDegrees(34.15, -119.15, 2000))); // Position the viewer to look near the airports LookAt lookAt = new LookAt().set(34.15, -119.15, 0, WorldWind.ABSOLUTE, 2e4 /*range*/, 0 /*heading*/, 45 /*tilt*/, 0 /*roll*/); wwd.getNavigator().setAsLookAt(wwd.getGlobe(), lookAt); return wwd; } /** * Helper method to create aircraft placemarks. */ private static Placemark createAircraftPlacemark(Position position) { Placemark placemark = Placemark.createWithImage(position, ImageSource.fromResource(R.drawable.aircraft_fighter)); placemark.getAttributes().setImageOffset(Offset.bottomCenter()).setImageScale(NORMAL_IMAGE_SCALE).setDrawLeader(true); placemark.setHighlightAttributes(new PlacemarkAttributes(placemark.getAttributes()).setImageScale(HIGHLIGHTED_IMAGE_SCALE)); return placemark; } /** * Helper method to create airport placemarks. */ private static Placemark createAirportPlacemark(Position position, String airportName) { Placemark placemark = Placemark.createWithImage(position, ImageSource.fromResource(R.drawable.airport_terminal)); placemark.getAttributes().setImageOffset(Offset.bottomCenter()).setImageScale(NORMAL_IMAGE_SCALE); placemark.setHighlightAttributes(new PlacemarkAttributes(placemark.getAttributes()).setImageScale(HIGHLIGHTED_IMAGE_SCALE)); placemark.setDisplayName(airportName); return placemark; } /** * This inner class is a custom WorldWindController that handles both picking and navigation via a combination of * the native WorldWind navigation gestures and Android gestures. This class' onTouchEvent method arbitrates * between pick events and globe navigation events. */ public class PickNavigateController extends BasicWorldWindowController { protected Object pickedObject; // last picked object from onDown events protected Object selectedObject; // last "selected" object from single tap /** * Assign a subclassed SimpleOnGestureListener to a GestureDetector to handle the "pick" events. */ protected GestureDetector pickGestureDetector = new GestureDetector(getContext().getApplicationContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent event) { pick(event); // Pick the object(s) at the tap location return false; // By not consuming this event, we allow it to pass on to the navigation gesture handlers } @Override public boolean onSingleTapUp(MotionEvent e) { toggleSelection(); // Highlight the picked object // By not consuming this event, we allow the "up" event to pass on to the navigation gestures, // which is required for proper zoom gestures. Consuming this event will cause the first zoom // gesture to be ignored. As an alternative, you can implement onSingleTapConfirmed and consume // event as you would expect, with the trade-off being a slight delay tap response. return false; } }); /** * Delegates events to the pick handler or the native WorldWind navigation handlers. */ @Override public boolean onTouchEvent(MotionEvent event) { // Allow pick listener to process the event first. boolean consumed = this.pickGestureDetector.onTouchEvent(event); // If event was not consumed by the pick operation, pass it on the globe navigation handlers if (!consumed) { // The super class performs the pan, tilt, rotate and zoom return super.onTouchEvent(event); } return consumed; } /** * Performs a pick at the tap location. ``` -------------------------------- ### Getting All Elements Except the Last in Scala Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/scala.html Returns a new collection containing all elements except the last one. If the collection is empty, it throws an `UnsupportedOperationException`. This operation is order-dependent. ```Scala /** * Selects all elements except the last. * $orderDependent * @return a $coll consisting of all elements of this $coll except the last one. * @throws `UnsupportedOperationException` if the $coll is empty. */ def init: Repr = { if (isEmpty) throw new UnsupportedOperationException("empty.init") var lst = head var follow = false val b = newBuilder b.sizeHint(this, -1) for (x <- this.seq) { if (follow) b += lst else follow = true lst = x } b.result } ``` -------------------------------- ### Getting All Elements Except the First (Tail) in Scala Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/scala.html Returns a new collection containing all elements except the first one. If the collection is empty, it throws an `UnsupportedOperationException`. This operation is order-dependent. ```Scala /** * Selects all elements except the first. * $orderDependent * @return a $coll consisting of all elements of this $coll except the first one. * @throws `UnsupportedOperationException` if the $coll is empty. */ override def tail: Repr = { if (isEmpty) throw new UnsupportedOperationException("empty.tail") drop(1) } ``` -------------------------------- ### Configure Camera View in Java Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/camera_view_tutorial.html This Java code snippet demonstrates how to create and configure a WorldWindow's camera to view a specific geographical position from an aircraft's perspective. It calculates the heading and tilt angles required to look from the aircraft's position to a target airport and sets the WorldWindow's navigator accordingly. Dependencies include the WorldWind SDK for Android. ```java package gov.nasa.worldwindx); import gov.nasa.worldwind.Camera; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.geom.Position; import gov.nasa.worldwind.globe.Globe; import gov.nasa.worldwind.WorldWind; public class CameraViewFragment extends BasicGlobeFragment { /** * Creates a new WorldWindow with its camera positioned at a given location and configured to point in a given * direction. */ @Override public WorldWindow createWorldWindow() { // Let the super class (BasicGlobeFragment) do the creation WorldWindow wwd = super.createWorldWindow(); // Create a view of Point Mugu airport as seen from an aircraft above Oxnard, CA. Position aircraft = new Position(34.2, -119.2, 3000); // Above Oxnard CA, altitude in meters Position airport = new Position(34.1192744, -119.1195850, 4.0); // KNTD airport, Point Mugu CA, altitude MSL // Compute heading and tilt angles from aircraft to airport Globe globe = wwd.getGlobe(); double heading = aircraft.greatCircleAzimuth(airport); double distanceRadians = aircraft.greatCircleDistance(airport); double distance = distanceRadians * globe.getRadiusAt(aircraft.latitude, aircraft.longitude); double tilt = Math.toDegrees(Math.atan(distance / aircraft.altitude)); // Create the new camera view Camera camera = new Camera(); camera.set(aircraft.latitude, aircraft.longitude, aircraft.altitude, WorldWind.ABSOLUTE, heading, tilt, 0); // No roll // Apply the view wwd.getNavigator().setAsCamera(globe, camera); // This works too! Using the fluid api to manipulate the Navigator's camera: // wwd.getNavigator() // .setLatitude(aircraft.latitude) // .setLongitude(aircraft.longitude) // .setAltitude(aircraft.altitude) // .setHeading(heading) // .setTilt(tilt); return wwd; } } ``` -------------------------------- ### LookAtViewFragment.java: Configure Camera for LookAt View Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/look_at_view_tutorial.html This Java code snippet, within the LookAtViewFragment class, demonstrates how to set up the WorldWindow's camera to look at a specific airport (LAX) from a simulated aircraft position above Santa Monica. It calculates the necessary camera parameters like range, heading, and tilt using great-circle calculations and applies them using a LookAt view. ```java package gov.nasa.worldwindx; ... public class LookAtViewFragment extends BasicGlobeFragment { /** * Creates a new WorldWindow with its camera configured to look at a given location from a given position. */ @Override public WorldWindow createWorldWindow() { // Let the super class (BasicGlobeFragment) do the creation WorldWindow wwd = super.createWorldWindow(); // Create a view of LAX airport as seen from an aircraft above Santa Monica, CA. Position aircraft = new Position(34.0158333, -118.4513056, 2500); // Aircraft above Santa Monica airport, altitude in meters Position airport = new Position(33.9424368, -118.4081222, 38.7); // LAX airport, Los Angeles CA, altitude MSL // Compute heading and distance from aircraft to airport Globe globe = wwd.getGlobe(); double heading = aircraft.greatCircleAzimuth(airport); double distanceRadians = aircraft.greatCircleDistance(airport); double distance = distanceRadians * globe.getRadiusAt(aircraft.latitude, aircraft.longitude); // Compute camera settings double altitude = aircraft.altitude - airport.altitude; double range = Math.sqrt(altitude * altitude + distance * distance); double tilt = Math.toDegrees(Math.atan(distance / aircraft.altitude)); // Apply the new view LookAt lookAt = new LookAt(); lookAt.set(airport.latitude, airport.longitude, airport.altitude, WorldWind.ABSOLUTE, range, heading, tilt, 0 /*roll*/); wwd.getNavigator().setAsLookAt(globe, lookAt); return wwd; } } ``` -------------------------------- ### Getting the Last Element Optionally in Scala Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/scala.html Returns an `Option` containing the last element of the collection if it is non-empty, otherwise returns `None`. This is a safe way to access the last element, avoiding exceptions for empty collections. It is order-dependent. ```Scala /** * Optionally selects the last element. * $orderDependent * @return the last element of this $coll$ if it is nonempty, `None` if it is empty. */ def lastOption: Option[A] = if (isEmpty) None else Some(last) ``` -------------------------------- ### Scala CodeMirror Editor Initialization Source: https://github.com/nasaworldwind/worldwindandroid/blob/develop/worldwind-tutorials/src/main/assets/codemirror-5.16.0/mode/clike/scala.html Initializes a CodeMirror editor instance for a textarea element with specific configurations for Scala mode, line numbers, and themes. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, theme: "ambiance", mode: "text/x-scala" }); ```