After running filter-branch, move root directory into sky/

This commit is contained in:
Collin Jackson
2015-07-16 11:54:25 -07:00
parent 82404e030a
commit 633b65010c
229 changed files with 51972 additions and 0 deletions

5
packages/flutter/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
.idea
.pub/
lib/_sdkext
packages
pubspec.lock

156
packages/flutter/BUILD.gn Normal file
View File

@@ -0,0 +1,156 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//mojo/public/dart/rules.gni")
dart_pkg("sky") {
sources = [
"CHANGELOG.md",
"bin/init.dart",
"lib/animation/animated_simulation.dart",
"lib/animation/animation_performance.dart",
"lib/animation/curves.dart",
"lib/animation/scroll_behavior.dart",
"lib/animation/timeline.dart",
"lib/assets/.gitignore",
"lib/assets/material-design-icons.sha1",
"lib/base/debug.dart",
"lib/base/hit_test.dart",
"lib/base/lerp.dart",
"lib/base/node.dart",
"lib/base/scheduler.dart",
"lib/download_material_design_icons",
"lib/editing/editable_string.dart",
"lib/editing/editable_text.dart",
"lib/editing/input.dart",
"lib/mojo/activity.dart",
"lib/mojo/asset_bundle.dart",
"lib/mojo/embedder.dart",
"lib/mojo/keyboard.dart",
"lib/mojo/net/fetch.dart",
"lib/mojo/net/image_cache.dart",
"lib/mojo/shell.dart",
"lib/painting/box_painter.dart",
"lib/painting/shadows.dart",
"lib/painting/text_style.dart",
"lib/rendering/auto_layout.dart",
"lib/rendering/block.dart",
"lib/rendering/box.dart",
"lib/rendering/flex.dart",
"lib/rendering/object.dart",
"lib/rendering/paragraph.dart",
"lib/rendering/sky_binding.dart",
"lib/rendering/stack.dart",
"lib/sky_tool",
"lib/theme/colors.dart",
"lib/theme/shadows.dart",
"lib/theme/theme_data.dart",
"lib/theme/typography.dart",
"lib/theme/view_configuration.dart",
"lib/widgets/animated_component.dart",
"lib/widgets/animation_builder.dart",
"lib/widgets/basic.dart",
"lib/widgets/block_viewport.dart",
"lib/widgets/button_base.dart",
"lib/widgets/card.dart",
"lib/widgets/checkbox.dart",
"lib/widgets/default_text_style.dart",
"lib/widgets/dialog.dart",
"lib/widgets/dismissable.dart",
"lib/widgets/drawer.dart",
"lib/widgets/drawer_divider.dart",
"lib/widgets/drawer_header.dart",
"lib/widgets/drawer_item.dart",
"lib/widgets/fixed_height_scrollable.dart",
"lib/widgets/flat_button.dart",
"lib/widgets/floating_action_button.dart",
"lib/widgets/icon.dart",
"lib/widgets/icon_button.dart",
"lib/widgets/ink_well.dart",
"lib/widgets/material.dart",
"lib/widgets/material_button.dart",
"lib/widgets/modal_overlay.dart",
"lib/widgets/navigator.dart",
"lib/widgets/popup_menu.dart",
"lib/widgets/popup_menu_item.dart",
"lib/widgets/radio.dart",
"lib/widgets/raised_button.dart",
"lib/widgets/scaffold.dart",
"lib/widgets/scrollable.dart",
"lib/widgets/scrollable_list.dart",
"lib/widgets/scrollable_viewport.dart",
"lib/widgets/snack_bar.dart",
"lib/widgets/switch.dart",
"lib/widgets/tabs.dart",
"lib/widgets/task_description.dart",
"lib/widgets/theme.dart",
"lib/widgets/toggleable.dart",
"lib/widgets/tool_bar.dart",
"lib/widgets/variable_height_scrollable.dart",
"lib/widgets/widget.dart",
"pubspec.yaml",
]
# List of mojom targets that the sky pkg exports
deps = [
"//mojo/services/asset_bundle/public/interfaces",
"//mojo/services/keyboard/public/interfaces",
"//sky/services/activity:interfaces",
"//sky/services/engine:interfaces",
]
datadeps = [
"//mojo/dart/mojo_services",
"//mojo/dart/mojom",
"//mojo/public/dart:mojo",
"//sky/engine/bindings",
"//sky/services/testing:interfaces",
"//sky/services/media:interfaces",
"//third_party/dart-pkg",
]
sdk_ext_directory = "$root_gen_dir/sky/bindings"
sdk_ext_files = [
"//sky/engine/bindings/sky_internals.dart",
"//sky/engine/bindings/builtin_natives.dart",
]
sdk_ext_mappings = [
"dart:sky,dart_sky.dart",
"dart:sky.internals,sky_internals.dart",
"dart:sky_builtin_natvies,builtin_natives.dart",
]
}
action("material_design_icons") {
input_dir = "lib/assets/material-design-icons"
output_dir = "$root_gen_dir/dart-pkg/sky/lib/assets"
stamp = "$target_gen_dir/material_design_icons_linked"
sources = [
"lib/assets/material-design-icons.sha1",
]
outputs = [
stamp,
]
script = "//build/symlink.py"
args = [
"--force",
rebase_path(input_dir, output_dir),
rebase_path(output_dir, root_build_dir),
"--touch",
rebase_path(stamp, root_build_dir),
]
deps = [
":sky",
]
}
group("sdk") {
deps = [
":sky",
":material_design_icons",
]
}

View File

@@ -0,0 +1,77 @@
## 0.0.18
- 41 changes: https://github.com/domokit/mojo/compare/246e279...c3119f6
## 0.0.17
- 18 changes: https://github.com/domokit/mojo/compare/e7433cf...8879bfd
## 0.0.16
- 27 changes: https://github.com/domokit/mojo/compare/e028733...e7433cf
## 0.0.15
- 6 changes: https://github.com/domokit/mojo/compare/4df2d39...e028733
## 0.0.14
- 42 changes: https://github.com/domokit/mojo/compare/3de9766...cf84c48
## 0.0.13
- 70 changes: https://github.com/domokit/mojo/compare/889091e...136e0d4
## 0.0.12
- 29 changes: https://github.com/domokit/mojo/compare/e25e3e2...432ce45
- Fixed sky_tool to work again.
## 0.0.11
- 197 changes: https://github.com/domokit/mojo/compare/bdbb0c7...fb1b726
## 0.0.10
- 23 changes: https://github.com/domokit/mojo/compare/1b7bcee...be9dad7
## 0.0.8
- Fix 2 crashes in SkyDemo.apk, updated widgets. 0.0.7 was skipped.
## 0.0.6
- First release after Dart summit. Adds new main.dart based workflow.
## 0.0.5+dart-summit-7
- Fix crash in sky_tool stop_tracing.
## 0.0.5+dart-summit-6
- Fix missing include in sky_tool causing failure.
## 0.0.5+dart-summit-5
- Added sky_tool start_tracing and stop_tracing.
## 0.0.5+dart-summit-4
- Added download_material_design_icons script.
## 0.0.5+dart-summit-3
- Fix typo in lib/sky_tool causing syntax error when run.
## 0.0.5+dart-summit-2
- Various demo fixes and added ChangeLogs.
## 0.0.5+dart-summit-1
- Branched from mojo trunk to stabalize for Dart summit.
## 0.0.2
- sdk_additions now includes previously missing imports.
- added lib/sky_tool, and supporting apks/SkyDemo.apk

217
packages/flutter/README.md Normal file
View File

@@ -0,0 +1,217 @@
Contributing
============
[sky_sdk](https://github.com/domokit/sky_sdk) is generated from the
[mojo repository](https://github.com/domokit/mojo) using
[deploy_sdk.py](https://github.com/domokit/mojo/blob/master/sky/tools/deploy_sdk.py)
Static files (including this README.md) are located under
[sky/sdk](https://github.com/domokit/mojo/tree/master/sky/sdk). Pull
requests and issue reports are glady accepted at the
[mojo repository](https://github.com/domokit/mojo)!
Sky
===
Sky is an experimental, high-performance UI framework for mobile apps. Sky helps
you create apps with beautiful user interfaces and high-quality interactive
design that run smoothly at 120 Hz.
Sky consists of two components:
1. *The Sky engine.* The engine is the core of the system. Written in C++, the
engine provides the muscle of the Sky system. The engine provides
several primitives, including a soft real-time scheduler and a hierarchical,
retained-mode graphics system, that let you build high-quality apps.
2. *The Sky framework.* The [framework](packages/sky/lib/framework) makes it
easy to build apps using Sky by providing familiar user interface widgets,
such as buttons, infinite lists, and animations, on top of the engine using
Dart. These extensible components follow a functional programming style
inspired by [React](http://facebook.github.io/react/).
We're still iterating on Sky heavily, which means the framework and underlying
engine are both likely to change in incompatible ways several times, but if
you're interested in trying out the system, this document can help you get
started.
Examples
--------
Sky uses Dart and Sky applications are
[Dart Packages](https://www.dartlang.org/docs/tutorials/shared-pkgs/).
Application creation starts by creating a new directory and
adding a [pubspec.yaml](https://www.dartlang.org/tools/pub/pubspec.html):
pubspec.yaml for your app:
```yaml
name: your_app_name
dependencies:
sky: any
```
Once the pubspec is in place, create a `lib` directory (where your dart code
will go), ensure that the 'dart' and 'pub' executables are on your $PATH and
run the following:
`pub get && pub run sky:init`.
Currently the Sky Engine assumes the entry point for your application is a
`main` function in a Dart file inside your package:
```dart
import 'package:sky/widgets/basic.dart';
class HelloWorldApp extends App {
Widget build() {
return new Text('Hello, world!');
}
}
void main() {
runApp(new HelloWorldApp());
}
```
Execution starts in `main`, which instructs the framework to run a new
instance of the `HelloWorldApp`. The framework then calls the `build()`
function on `HelloWorldApp` to create a tree of widgets, some of which might
be other `Components`, which in turn have `build()` functions that generate
more widgets iteratively to create the widget hierarchy.
Later, if a `Component` changes state, the framework calls that component's
`build()` function again to create a new widget tree. The framework diffs the
new widget tree against the old widget tree and any differences are applyed
to the underlying render tree.
* To learn more about the widget system, please see the
[widgets tutorial](lib/widgets/README.md).
* To learn how to run Sky on your device, please see the
[Running a Sky application](#running-a-sky-application) section in this
document.
* To dive into examples, please see the [examples directory](example/).
Services
--------
Sky apps can access services from the host operating system using Mojo IPC. For
example, you can access the network using the `network_service.mojom` interface.
Although you can use these low-level interfaces directly, you might prefer to
access these services via libraries in the framework. For example, the
`fetch.dart` library wraps the underlying `network_service.mojom` in an
ergonomic interface:
```dart
import 'package:sky/mojo/net/fetch.dart';
main() async {
Response response = await fetchBody('example.txt');
print(response.bodyAsString());
}
```
Set up your computer
--------------------
1. Install the Dart SDK:
- https://www.dartlang.org/tools/download.html
2. Install the `adb` tool from the Android SDK:
- https://developer.android.com/sdk/installing/index.html
3. Install the Sky SDK:
- `git clone https://github.com/domokit/sky_sdk.git`
4. Ensure that `$DART_SDK` is set to the path of your Dart SDK and `adb`
(inside `platform-tools` in the android sdk) is in your `$PATH`.
Set up your device
------------------
Currently Sky requires an Android device running the Lollipop (or newer) version
of the Android operating system.
1. Enable developer mode on your device by visiting `Settings > About phone`
and tapping the `Build number` field five times.
2. Enable `USB debugging` in `Settings > Developer options`.
3. Using a USB cable, plug your phone into your computer. If prompted on your
device, authorize your computer to access your device.
Running a Sky application
-------------------------
The `sky` pub package includes a `sky_tool` script to assist in running
Sky applications inside the `SkyDemo.apk` harness. The `sky_tool` script
expects to be run from the root directory of your application pub package. To
run one of the examples in this SDK, try:
1. `cd example/stocks`
2. `pub get` to set up a copy of the sky package in the app directory.
3. `./packages/sky/sky_tool start` to start the dev server and upload your
app to the device.
(NOTE: add a `--install` flag to install `SkyDemo.apk` if it is not already
installed on the device.)
4. Use `adb logcat` to view any errors or Dart `print()` output from the app.
`adb logcat -s chromium` can be used to filter only adb messages from
`SkyDemo.apk` (which for
[legacy reasons](https://github.com/domokit/mojo/issues/129) still uses the
android log tag `chromium`).
Measuring Performance
---------------------
Sky has support for generating trace files compatible with
[Chrome's about:tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool).
`packages/sky/sky_tool start_tracing` and `packages/sky/sky_tool stop_tracing`
are the commands to use.
Due to https://github.com/domokit/mojo/issues/127 tracing currently
requires root access on the device.
Debugging
---------
Sky uses [Observatory](https://www.dartlang.org/tools/observatory/) for
debugging and profiling. While running your Sky app using `sky_tool`, you can
access Observatory by navigating your web browser to http://localhost:8181/.
Building a standalone MyApp
---------------------------
Although it is possible to bundle the Sky Engine in your own app (instead of
running your code inside SkyDemo.apk), right now doing so is difficult.
There is one example of doing so if you're feeling brave:
https://github.com/domokit/mojo/tree/master/sky/sdk/example/stocks
Eventually we plan to make this much easier and support platforms other than
Android, but that work is yet in progress.
Adding Services to MyApp
------------------------
[Mojo IPC](https://github.com/domokit/mojo) is an inter-process-communication
system designed to provide cross-thread, cross-process, and language-agnostic
communication between applications. Sky uses Mojo IPC to make it possible
to write UI code in Dart and yet depend on networking code, etc. written in
another language. Services are replicable, meaning that Dart code
written to use the `network_service` remains portable to any platform
(iOS, Android, etc.) by simply providing a 'natively' written `network_service`.
Embedders of the Sky Engine and consumers of the Sky Framework can use this
same mechanism to expose not only existing services like the
[Keyboard](https://github.com/domokit/mojo/blob/master/mojo/services/keyboard/public/interfaces/keyboard.mojom)
service to allow Sky Framework Dart code to interface with the underlying
platform's Keyboard, but also to expose any additional non-Dart business logic
to Sky/Dart UI code.
As an example, [SkyApplication](https://github.com/domokit/mojo/blob/master/sky/shell/org/domokit/sky/shell/SkyApplication.java)
exposes a mojo `network_service` (required by Sky Engine C++ code)
[SkyDemoApplication](https://github.com/domokit/mojo/blob/master/sky/apk/demo/org/domokit/sky/demo/SkyDemoApplication.java)
additionally exposes `keyboard_service` and `sensor_service` for use by the Sky
Framework from Dart.

View File

@@ -0,0 +1,17 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/*
* This script should be invoked via 'pub run' after 'pub get':
* $ pub run sky:init
* NOTE: The 'dart' executable must be on your $PATH for this script to work.
*/
import 'dart:io';
main(List<String> arguments) {
ProcessResult result = Process.runSync('dart', ['-p', 'packages', 'packages/mojom/generate.dart']);
stdout.write(result.stdout);
stderr.write(result.stderr);
}

View File

@@ -0,0 +1,16 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
group("example") {
testonly = true
deps = [
"//sky/sdk/example/demo_launcher",
"//sky/sdk/example/game",
"//sky/sdk/example/mine_digger",
"//sky/sdk/example/rendering",
"//sky/sdk/example/stocks",
"//sky/sdk/example/widgets",
]
}

View File

@@ -0,0 +1,16 @@
Sky Examples
============
This directory contains several examples of using Sky. Each of these is an
individual Dart application package. If you wish to run them with `sky_tool`
then you will want to run `pub get` inside their directory before running
`./packages/sky/sky_tool start`.
1. *Hello, world.* The [hello world app](hello_world) is a basic app that shows
the text "hello, world."
2. *Stocks.* The [stocks app](stocks) is an example of a typical mobile app
built using Sky. The app shows a list of all the stocks in the NASDAQ.
3. *Widgets.* The [widgets app](widgets) contains a number of Sky widgets so
you can experiment with them in a simple container.

View File

@@ -0,0 +1,106 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/theme/typography.dart' as typography;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/default_text_style.dart';
import 'package:sky/widgets/theme.dart';
import 'package:sky/widgets/widget.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/scaffold.dart';
import 'package:sky/widgets/tool_bar.dart';
import 'package:sky/widgets/icon_button.dart';
import 'package:sky/widgets/floating_action_button.dart';
import 'package:sky/widgets/icon.dart';
import 'package:sky/widgets/material.dart';
import 'package:sky/editing/input.dart';
import 'package:sky/widgets/scrollable_viewport.dart';
class Field extends Component {
Field({this.icon: null, this.placeholder: null});
String icon;
String placeholder;
Widget build() {
return new Flex([
new Padding(
padding: const EdgeDims.symmetric(horizontal: 16.0),
child: new Icon(type:icon, size:24)
),
new Flexible(child:new Input(placeholder:placeholder, focused:false))
],
direction: FlexDirection.horizontal
);
}
}
class AddressBookApp extends App {
Widget buildToolBar() {
return new ToolBar(
left: new IconButton(icon: "navigation/arrow_back"),
right: [new IconButton(icon: "navigation/check")]
);
}
Widget buildFloatingActionButton() {
return new FloatingActionButton(
child: new Icon(type: 'image/photo_camera', size: 24),
backgroundColor: Theme.of(this).accentColor
);
}
Widget buildBody() {
return new Material(
child: new ScrollableBlock([
new AspectRatio(
aspectRatio: 16.0 / 9.0,
child: new Container(
decoration: new BoxDecoration(backgroundColor: colors.Purple[300])
)
),
new Field(icon:"social/person", placeholder:"Name"),
new Field(icon: "communication/phone", placeholder:"Phone"),
new Field(icon: "communication/email", placeholder:"Email"),
new Field(icon: "maps/place", placeholder:"Address"),
new Field(icon: "av/volume_up", placeholder:"Ringtone"),
new Field(icon: "content/add", placeholder:"Add note"),
])
);
}
Widget buildMain() {
return new Scaffold(
toolbar: buildToolBar(),
body: buildBody(),
floatingActionButton: buildFloatingActionButton()
);
}
Widget build() {
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Teal,
accentColor: colors.PinkAccent[100]
);
return new Theme(
data: theme,
child: new DefaultTextStyle(
style: typography.error, // if you see this, you've forgotten to correctly configure the text style!
child: new TaskDescription(
label: 'Address Book',
child: buildMain()
)
)
);
}
}
void main() {
runApp(new AddressBookApp());
}

View File

@@ -0,0 +1,28 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/sky_app.gni")
sky_app("demo_launcher") {
main_dart = "lib/main.dart"
manifest = "sky.yaml"
if (is_android) {
apk_name = "SkyDemo"
bundles = [
"//sky/sdk/example/fitness",
"//sky/sdk/example/game",
"//sky/sdk/example/mine_digger",
"//sky/sdk/example/rendering:interactive_flex",
"//sky/sdk/example/stocks",
"//sky/sdk/example/widgets:cards",
]
deps = [
"//sky/sdk/example/demo_launcher/apk:java",
"//sky/sdk/example/demo_launcher/apk:resources",
]
}
}

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.domokit.sky.demo" android:versionCode="18" android:versionName="0.0.18">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
<application android:icon="@mipmap/ic_launcher" android:label="Sky" android:name="SkyDemoApplication">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize" android:documentLaunchMode="always" android:hardwareAccelerated="true" android:launchMode="standard" android:name="SkyDemoActivity" android:theme="@android:style/Theme.Black.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,31 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_android)
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
android_library("java") {
java_files = [
"org/domokit/sky/demo/SkyDemoActivity.java",
"org/domokit/sky/demo/SkyDemoApplication.java",
]
deps = [
"//base:base_java",
"//mojo/public/java:bindings",
"//mojo/public/java:system",
"//mojo/services/sensors/public/interfaces:interfaces_java",
"//services/sensors:sensors_lib",
"//sky/services/media:media_lib",
"//sky/services/media:interfaces_java",
"//sky/shell:java",
]
}
android_resources("resources") {
resource_dirs = [ "res" ]
android_manifest = "AndroidManifest.xml"
}

View File

@@ -0,0 +1,6 @@
Icon image comes from:
https://openclipart.org/detail/30073/tango%20weather%20few%20clouds
and is public domain.
Icon resources were generated using:
http://romannurik.github.io/AndroidAssetStudio/icons-launcher.html

View File

@@ -0,0 +1,31 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.domokit.sky.demo;
import android.content.Intent;
import org.domokit.sky.shell.SkyActivity;
/**
* Main activity for SkyDemo.
*/
public class SkyDemoActivity extends SkyActivity {
@Override
protected void onSkyReady() {
Intent intent = getIntent();
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
String bundleName = intent.getStringExtra("bundleName");
if (bundleName != null && loadBundleByName(bundleName)) {
return;
}
loadUrl(intent.getDataString());
return;
}
super.onSkyReady();
}
}

View File

@@ -0,0 +1,57 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.domokit.sky.demo;
import android.content.Context;
import org.chromium.mojo.sensors.SensorServiceImpl;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojom.media.MediaService;
import org.chromium.mojom.sensors.SensorService;
import org.domokit.media.MediaServiceImpl;
import org.domokit.sky.shell.ResourceExtractor;
import org.domokit.sky.shell.ServiceFactory;
import org.domokit.sky.shell.ServiceRegistry;
import org.domokit.sky.shell.SkyApplication;
/**
* SkyDemo implementation of {@link android.app.Application}
*/
public class SkyDemoApplication extends SkyApplication {
private static final String[] DEMO_RESOURCES = {
"cards.skyx",
"fitness.skyx",
"game.skyx",
"interactive_flex.skyx",
"mine_digger.skyx",
"stocks.skyx",
};
@Override
protected void onBeforeResourceExtraction(ResourceExtractor extractor) {
super.onBeforeResourceExtraction(extractor);
extractor.addResources(DEMO_RESOURCES);
}
@Override
public void onServiceRegistryAvailable(ServiceRegistry registry) {
super.onServiceRegistryAvailable(registry);
registry.register(SensorService.MANAGER.getName(), new ServiceFactory() {
@Override
public void connectToService(Context context, Core core, MessagePipeHandle pipe) {
SensorService.MANAGER.bind(new SensorServiceImpl(context), pipe);
}
});
registry.register(MediaService.MANAGER.getName(), new ServiceFactory() {
@Override
public void connectToService(Context context, Core core, MessagePipeHandle pipe) {
MediaService.MANAGER.bind(new MediaServiceImpl(context, core), pipe);
}
});
}
}

View File

@@ -0,0 +1 @@
First version published to production from our service account.

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@@ -0,0 +1,206 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/mojo/activity.dart' as activity;
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/painting/box_painter.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/theme/typography.dart' as typography;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/card.dart';
import 'package:sky/widgets/material.dart';
import 'package:sky/widgets/scaffold.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/theme.dart';
import 'package:sky/widgets/tool_bar.dart';
import 'package:sky/widgets/scrollable_list.dart';
import 'package:sky/widgets/ink_well.dart';
AssetBundle _initBundle() {
if (rootBundle != null)
return rootBundle;
const String _kAssetBase = '..';
return new NetworkAssetBundle(Uri.base.resolve(_kAssetBase));
}
final AssetBundle _bundle = _initBundle();
void launch(String relativeUrl, String bundle) {
// TODO(eseidel): This is a hack to keep non-skyx examples working for now:
Uri productionBase = Uri.parse(
'https://domokit.github.io/example/demo_launcher/lib/main.dart');
Uri base = rootBundle == null ? Uri.base : productionBase;
Uri url = base.resolve(relativeUrl);
activity.ComponentName component = new activity.ComponentName()
..packageName = 'org.domokit.sky.demo'
..className = 'org.domokit.sky.demo.SkyDemoActivity';
activity.Intent intent = new activity.Intent()
..action = 'android.intent.action.VIEW'
..component = component
..flags = activity.MULTIPLE_TASK | activity.NEW_DOCUMENT
..url = url.toString();
if (bundle != null) {
activity.StringExtra extra = new activity.StringExtra()
..name = 'bundleName'
..value = bundle;
intent.stringExtras = [extra];
}
activity.startActivity(intent);
}
class SkyDemo {
String name;
String href;
String bundle;
String description;
typography.TextTheme textTheme;
BoxDecoration decoration;
SkyDemo({ this.name, this.href, this.bundle, this.description, this.textTheme, this.decoration });
}
List<SkyDemo> demos = [
new SkyDemo(
name: 'Stocks',
href: '../../stocks/lib/main.dart',
bundle: 'stocks.skyx',
description: 'Multi-screen app with scrolling list',
textTheme: typography.black,
decoration: new BoxDecoration(
backgroundImage: new BackgroundImage(
image: _bundle.loadImage('assets/stocks_thumbnail.png'),
fit: BackgroundFit.cover
)
)
),
new SkyDemo(
name: 'Asteroids',
href: '../../game/main.dart',
bundle: 'game.skyx',
description: '2D game using sprite sheets to achieve high performance',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundImage: new BackgroundImage(
image: _bundle.loadImage('assets/game_thumbnail.png'),
fit: BackgroundFit.cover
)
)
),
new SkyDemo(
name: 'Fitness',
href: '../../fitness/lib/main.dart',
bundle: 'fitness.skyx',
description: 'Collin should write a nice description',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundColor: const Color(0xFF0081C6)
)
),
new SkyDemo(
name: 'Cards',
href: '../../widgets/card_collection.dart',
bundle: 'cards.skyx',
description: 'Demo of interactive Cards',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundColor: const Color(0xFF0081C6)
)
),
new SkyDemo(
name: 'Interactive Text',
href: '../../rendering/interactive_flex.dart',
bundle: 'interactive_flex.skyx',
description: 'Swipe to reflow the app',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundColor: const Color(0xFF0081C6)
)
),
// new SkyDemo(
// 'Touch Demo', '../../rendering/touch_demo.dart', 'Simple example showing handling of touch events at a low level'),
new SkyDemo(
name: 'Minedigger Game',
href: '../../mine_digger/lib/main.dart',
bundle: 'mine_digger.skyx',
description: 'Clone of the classic Minesweeper game',
textTheme: typography.white
),
// TODO(jackson): This doesn't seem to be working
// new SkyDemo('Licenses', 'LICENSES.sky'),
];
const double kCardHeight = 120.0;
const EdgeDims kListPadding = const EdgeDims.all(4.0);
class DemoList extends Component {
Widget buildCardContents(SkyDemo demo) {
return new Container(
decoration: demo.decoration,
child: new InkWell(
child: new Container(
margin: const EdgeDims.all(24.0),
child: new Flex([
new Text(demo.name, style: demo.textTheme.title),
new Flexible(
child: new Text(demo.description, style: demo.textTheme.subhead)
)
],
direction: FlexDirection.vertical,
alignItems: FlexAlignItems.start)
)
)
);
}
Widget buildDemo(SkyDemo demo) {
return new Listener(
key: demo.name,
onGestureTap: (_) => launch(demo.href, demo.bundle),
child: new Container(
height: kCardHeight,
child: new Card(
child: buildCardContents(demo)
)
)
);
}
Widget build() {
return new ScrollableList<SkyDemo>(
items: demos,
itemHeight: kCardHeight,
itemBuilder: buildDemo,
padding: kListPadding
);
}
}
class SkyHome extends App {
Widget build() {
return new Theme(
data: new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Teal
),
child: new TaskDescription(
label: 'Sky Demos',
child: new Scaffold(
toolbar: new ToolBar(center: new Text('Sky Demos')),
body: new Material(
type: MaterialType.canvas,
child: new DemoList()
)
)
)
);
}
}
void main() {
runApp(new SkyHome());
}

View File

@@ -0,0 +1,4 @@
assets:
- assets/game_thumbnail.png
- assets/sector_thumbnail.png
- assets/stocks_thumbnail.png

View File

@@ -0,0 +1,13 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_android)
import("//sky/build/sky_app.gni")
sky_app("fitness") {
apk_name = "Fitness"
main_dart = "lib/main.dart"
manifest = "sky.yaml"
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.domokit.fitness">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name="org.domokit.sky.shell.SkyApplication" android:label="Fitness">
<activity android:name="org.domokit.sky.shell.SkyActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
android:hardwareAccelerated="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,6 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
enum FitnessMode { measure, run }
enum BackupMode { enabled, disabled }

View File

@@ -0,0 +1,205 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/painting/text_style.dart';
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/drawer.dart';
import 'package:sky/widgets/drawer_divider.dart';
import 'package:sky/widgets/drawer_header.dart';
import 'package:sky/widgets/drawer_item.dart';
import 'package:sky/widgets/floating_action_button.dart';
import 'package:sky/widgets/icon_button.dart';
import 'package:sky/widgets/icon.dart';
import 'package:sky/widgets/material.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/scaffold.dart';
import 'package:sky/widgets/snack_bar.dart';
import 'package:sky/widgets/theme.dart';
import 'package:sky/widgets/tool_bar.dart';
import 'package:sky/widgets/widget.dart';
import 'fitness_types.dart';
import 'measurement.dart';
class HomeFragment extends StatefulComponent {
HomeFragment(this.navigator, this.userData);
Navigator navigator;
List<Measurement> userData;
FitnessMode _fitnessMode = FitnessMode.measure;
void initState() {
// if (debug)
// new Timer(new Duration(seconds: 1), dumpState);
super.initState();
}
void syncFields(HomeFragment source) {
navigator = source.navigator;
userData = source.userData;
}
bool _isShowingSnackBar = false;
bool _isRunning = false;
void _handleFitnessModeChange(FitnessMode value) {
setState(() {
_fitnessMode = value;
});
}
Drawer buildDrawer() {
if (_drawerStatus == DrawerStatus.inactive)
return null;
return new Drawer(
showing: _drawerShowing,
level: 3,
onStatusChanged: _handleDrawerStatusChange,
navigator: navigator,
children: [
new DrawerHeader(children: [new Text('Fitness')]),
new DrawerItem(
icon: 'action/assessment',
onPressed: () => _handleFitnessModeChange(FitnessMode.measure),
selected: _fitnessMode == FitnessMode.measure,
children: [new Text('Measure')]),
new DrawerItem(
icon: 'maps/directions_run',
onPressed: () => _handleFitnessModeChange(FitnessMode.run),
selected: _fitnessMode == FitnessMode.run,
children: [new Text('Run')]),
new DrawerDivider(),
new DrawerItem(
icon: 'action/settings',
onPressed: _handleShowSettings,
children: [new Text('Settings')]),
new DrawerItem(
icon: 'action/help',
children: [new Text('Help & Feedback')])
]
);
}
bool _drawerShowing = false;
DrawerStatus _drawerStatus = DrawerStatus.inactive;
void _handleOpenDrawer() {
setState(() {
_drawerShowing = true;
_drawerStatus = DrawerStatus.active;
});
}
void _handleDrawerStatusChange(DrawerStatus status) {
setState(() {
_drawerStatus = status;
});
}
void _handleShowSettings() {
navigator.pop();
navigator.pushNamed('/settings');
}
// TODO(jackson): We should be localizing
String get fitnessModeTitle {
switch(_fitnessMode) {
case FitnessMode.measure: return "Measure";
case FitnessMode.run: return "Run";
}
}
Widget buildToolBar() {
return new ToolBar(
left: new IconButton(
icon: "navigation/menu",
onPressed: _handleOpenDrawer),
center: new Text(fitnessModeTitle)
);
}
Widget buildBody() {
TextStyle style = Theme.of(this).text.title;
switch (_fitnessMode) {
case FitnessMode.measure:
return new Material(
type: MaterialType.canvas,
child: new Flex(
[new Text("No measurements yet.\nAdd a new one!", style: style)],
justifyContent: FlexJustifyContent.center
)
);
case FitnessMode.run:
return new Material(
type: MaterialType.canvas,
child: new Flex([
new Text(_isRunning ? "Go go go!" : "Start a new run!", style: style)
], justifyContent: FlexJustifyContent.center)
);
}
}
void _handleUndo() {
setState(() {
_isShowingSnackBar = false;
});
}
Widget buildSnackBar() {
if (!_isShowingSnackBar)
return null;
return new SnackBar(
content: new Text("Measurement added!"),
actions: [new SnackBarAction(label: "UNDO", onPressed: _handleUndo)]
);
}
void _handleMeasurementAdded() {
setState(() {
_isShowingSnackBar = true;
});
}
void _handleRunStarted() {
setState(() {
_isRunning = true;
});
}
void _handleRunStopped() {
setState(() {
_isRunning = false;
});
}
Widget buildFloatingActionButton() {
switch (_fitnessMode) {
case FitnessMode.measure:
return new FloatingActionButton(
child: new Icon(type: 'content/add', size: 24),
onPressed: _handleMeasurementAdded
);
case FitnessMode.run:
return new FloatingActionButton(
child: new Icon(
type: _isRunning ? 'av/stop' : 'maps/directions_run',
size: 24
),
onPressed: _isRunning ? _handleRunStopped : _handleRunStarted
);
}
}
Widget build() {
return new Scaffold(
toolbar: buildToolBar(),
body: buildBody(),
snackBar: buildSnackBar(),
floatingActionButton: buildFloatingActionButton(),
drawer: buildDrawer()
);
}
}

View File

@@ -0,0 +1,75 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/theme.dart';
import 'package:sky/widgets/widget.dart';
import 'package:sky/widgets/task_description.dart';
import 'measurement.dart';
import 'home.dart';
import 'settings.dart';
import 'fitness_types.dart';
class FitnessApp extends App {
NavigationState _navigationState;
void initState() {
_navigationState = new NavigationState([
new Route(
name: '/',
builder: (navigator, route) => new HomeFragment(navigator, _userData)
),
new Route(
name: '/settings',
builder: (navigator, route) => new SettingsFragment(navigator, backupSetting, settingsUpdater)
),
]);
super.initState();
}
void onBack() {
if (_navigationState.hasPrevious()) {
setState(() {
_navigationState.pop();
});
} else {
super.onBack();
}
}
BackupMode backupSetting = BackupMode.disabled;
void settingsUpdater({ BackupMode backup }) {
setState(() {
if (backup != null)
backupSetting = backup;
});
}
final List<Measurement> _userData = [
new Measurement(when: new DateTime.now(), weight: 400.0)
];
Widget build() {
return new Theme(
data: new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Indigo,
accentColor: colors.PinkAccent[200]
),
child: new TaskDescription(
label: 'Fitness',
child: new Navigator(_navigationState)
)
);
}
}
void main() {
runApp(new FitnessApp());
}

View File

@@ -0,0 +1,11 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
class Measurement {
final DateTime when;
final double weight;
Measurement({ this.when, this.weight });
}

View File

@@ -0,0 +1,80 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/drawer_item.dart';
import 'package:sky/widgets/switch.dart';
import 'package:sky/widgets/icon_button.dart';
import 'package:sky/widgets/material.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/scaffold.dart';
import 'package:sky/widgets/scrollable_viewport.dart';
import 'package:sky/widgets/tool_bar.dart';
import 'package:sky/widgets/theme.dart';
import 'fitness_types.dart';
typedef void SettingsUpdater({
BackupMode backup
});
class SettingsFragment extends Component {
SettingsFragment(this.navigator, this.backup, this.updater);
final Navigator navigator;
final BackupMode backup;
final SettingsUpdater updater;
bool showModeDialog = false;
void _handleBackupChanged(bool value) {
if (updater != null)
updater(backup: value ? BackupMode.enabled : BackupMode.disabled);
}
Widget buildToolBar() {
return new ToolBar(
left: new IconButton(
icon: "navigation/arrow_back",
onPressed: navigator.pop),
center: new Text('Settings')
);
}
Widget buildSettingsPane() {
return new Material(
type: MaterialType.canvas,
child: new ScrollableViewport(
child: new Container(
padding: const EdgeDims.symmetric(vertical: 20.0),
child: new Block([
new DrawerItem(
onPressed: () { _handleBackupChanged(!(backup == BackupMode.enabled)); },
children: [
new Flexible(child: new Text('Back up data to the cloud')),
new Switch(value: backup == BackupMode.enabled, onChanged: _handleBackupChanged)
]
),
new DrawerItem(
children: [
new Flex([
new Text('Height'),
new Text("6'2\"", style: Theme.of(this).text.caption),
], direction: FlexDirection.vertical, alignItems: FlexAlignItems.start)
]
),
])
)
)
);
}
Widget build() {
return new Scaffold(
toolbar: buildToolBar(),
body: buildSettingsPane()
);
}
}

View File

@@ -0,0 +1,10 @@
material-design-icons:
- name: action/assessment
- name: action/help
- name: action/settings
- name: content/add
- name: maps/directions_run
- name: navigation/arrow_back
- name: navigation/menu
- name: navigation/more_vert
- name: av/stop

View File

@@ -0,0 +1,18 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/sky_app.gni")
sky_app("game") {
main_dart = "main.dart"
manifest = "sky.yaml"
if (is_android) {
apk_name = "Asteroids"
deps = [
"//sky/sdk/example/game/apk:resources",
]
}
}

View File

@@ -0,0 +1,2 @@
Assets for this game are taken from Galactic Guardian:
https://github.com/slembcke/GalacticGuardian.spritebuilder

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.domokit.asteroids">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="@mipmap/ic_launcher" android:name="org.domokit.sky.shell.SkyApplication" android:label="Asteroids">
<activity android:name="org.domokit.sky.shell.SkyActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
android:hardwareAccelerated="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,12 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_android)
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
android_resources("resources") {
resource_dirs = [ "res" ]
android_manifest = "AndroidManifest.xml"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 859 KiB

View File

@@ -0,0 +1,219 @@
{"frames": [
{
"filename": "asteroid_big_0.nrm.png",
"frame": {"x":2,"y":260,"w":200,"h":188},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":200,"h":188},
"sourceSize": {"w":200,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_0.png",
"frame": {"x":260,"y":193,"w":200,"h":167},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":0,"y":21,"w":200,"h":167},
"sourceSize": {"w":200,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_1.nrm.png",
"frame": {"x":451,"y":2,"w":204,"h":166},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":204,"h":166},
"sourceSize": {"w":204,"h":166},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_1.png",
"frame": {"x":657,"y":2,"w":204,"h":166},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":204,"h":166},
"sourceSize": {"w":204,"h":166},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_2.nrm.png",
"frame": {"x":462,"y":170,"w":194,"h":165},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":194,"h":165},
"sourceSize": {"w":194,"h":165},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_2.png",
"frame": {"x":658,"y":170,"w":194,"h":165},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":0,"y":2,"w":194,"h":165},
"sourceSize": {"w":194,"h":167},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_0.nrm.png",
"frame": {"x":204,"y":362,"w":102,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":102,"h":84},
"sourceSize": {"w":102,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_0.png",
"frame": {"x":308,"y":362,"w":102,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":102,"h":84},
"sourceSize": {"w":102,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_1.nrm.png",
"frame": {"x":854,"y":213,"w":96,"h":102},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":96,"h":102},
"sourceSize": {"w":96,"h":102},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_1.png",
"frame": {"x":854,"y":317,"w":96,"h":102},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":0,"y":0,"w":96,"h":102},
"sourceSize": {"w":96,"h":106},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_2.nrm.png",
"frame": {"x":740,"y":337,"w":109,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":109,"h":84},
"sourceSize": {"w":109,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_2.png",
"frame": {"x":740,"y":423,"w":109,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":109,"h":84},
"sourceSize": {"w":109,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "explosion_flare.png",
"frame": {"x":863,"y":2,"w":56,"h":209},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":4,"y":0,"w":56,"h":209},
"sourceSize": {"w":64,"h":256},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "explosion_particle.png",
"frame": {"x":2,"y":450,"w":36,"h":60},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":14,"y":1,"w":36,"h":60},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "explosion_ring.png",
"frame": {"x":2,"y":2,"w":256,"h":256},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":256,"h":256},
"sourceSize": {"w":256,"h":256},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "fire_particle.png",
"frame": {"x":40,"y":450,"w":55,"h":55},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":4,"y":4,"w":55,"h":55},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "laser.png",
"frame": {"x":204,"y":260,"w":37,"h":76},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":37,"h":76},
"sourceSize": {"w":37,"h":76},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "shield.png",
"frame": {"x":260,"y":2,"w":189,"h":189},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":189,"h":189},
"sourceSize": {"w":189,"h":189},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "ship.nrm.png",
"frame": {"x":462,"y":337,"w":137,"h":167},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":137,"h":167},
"sourceSize": {"w":137,"h":167},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "ship.png",
"frame": {"x":601,"y":337,"w":137,"h":167},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":25,"y":10,"w":137,"h":167},
"sourceSize": {"w":188,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "star_0.png",
"frame": {"x":204,"y":448,"w":62,"h":62},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":1,"y":1,"w":62,"h":62},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "star_1.png",
"frame": {"x":268,"y":448,"w":62,"h":62},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":1,"y":1,"w":62,"h":62},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "star_2.png",
"frame": {"x":332,"y":448,"w":62,"h":62},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":1,"y":1,"w":62,"h":62},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
}],
"meta": {
"app": "http://www.codeandweb.com/texturepacker",
"version": "1.0",
"image": "sprites.png",
"format": "RGBA8888",
"size": {"w":952,"h":512},
"scale": "1",
"smartupdate": "$TexturePacker:SmartUpdate:342fc72defddab59bb356b48894e2931:ecb4b4fa7772ea6a35788ebf670ca27c:1eabdf11f75e3a4fe3147baf7b5be24b$"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 523 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

View File

@@ -0,0 +1,470 @@
part of sprites;
typedef void ActionCallback();
abstract class Action {
Object _tag;
bool _finished = false;
bool _added = false;
void step(double dt);
void update(double t) {
}
void _reset() {
_finished = false;
}
double get duration => 0.0;
}
abstract class ActionInterval extends Action {
double _duration;
bool _firstTick = true;
double _elapsed = 0.0;
double get duration => _duration;
Curve curve;
ActionInterval([this._duration = 0.0, this.curve]);
void step(double dt) {
if (_firstTick) {
_firstTick = false;
} else {
_elapsed += dt;
}
double t;
if (this._duration == 0.0) {
t = 1.0;
} else {
t = (_elapsed / _duration).clamp(0.0, 1.0);
}
if (curve == null) {
update(t);
} else {
update(curve.transform(t));
}
if (t >= 1.0) _finished = true;
}
}
class ActionRepeat extends ActionInterval {
final int numRepeats;
final ActionInterval action;
int _lastFinishedRepeat = -1;
ActionRepeat(this.action, this.numRepeats) {
_duration = action.duration * numRepeats;
}
void update(double t) {
int currentRepeat = math.min((t * numRepeats.toDouble()).toInt(), numRepeats - 1);
for (int i = math.max(_lastFinishedRepeat, 0); i < currentRepeat; i++) {
if (!action._finished) action.update(1.0);
action._reset();
}
_lastFinishedRepeat = currentRepeat;
double ta = (t * numRepeats.toDouble()) % 1.0;
action.update(ta);
if (t >= 1.0) {
action.update(1.0);
action._finished = true;
}
}
}
class ActionRepeatForever extends Action {
final ActionInterval action;
double _elapsedInAction = 0.0;
ActionRepeatForever(this.action);
step(double dt) {
_elapsedInAction += dt;
while (_elapsedInAction > action.duration) {
_elapsedInAction -= action.duration;
if (!action._finished) action.update(1.0);
action._reset();
}
_elapsedInAction = math.max(_elapsedInAction, 0.0);
double t;
if (action._duration == 0.0) {
t = 1.0;
} else {
t = (_elapsedInAction / action._duration).clamp(0.0, 1.0);
}
action.update(t);
}
}
class ActionSequence extends ActionInterval {
Action _a;
Action _b;
double _split;
ActionSequence(List<Action> actions) {
assert(actions.length >= 2);
if (actions.length == 2) {
// Base case
_a = actions[0];
_b = actions[1];
} else {
_a = actions[0];
_b = new ActionSequence(actions.sublist(1));
}
// Calculate split and duration
_duration = _a.duration + _b.duration;
if (_duration > 0) {
_split = _a.duration / _duration;
} else {
_split = 1.0;
}
}
void update(double t) {
if (t < _split) {
// Play first action
double ta;
if (_split > 0.0) {
ta = (t / _split).clamp(0.0, 1.0);
} else {
ta = 1.0;
}
_updateWithCurve(_a, ta);
} else if (t >= 1.0) {
// Make sure everything is finished
if (!_a._finished) _finish(_a);
if (!_b._finished) _finish(_b);
} else {
// Play second action, but first make sure the first has finished
if (!_a._finished) _finish(_a);
double tb;
if (_split < 1.0) {
tb = (1.0 - (1.0 - t) / (1.0 - _split)).clamp(0.0, 1.0);
} else {
tb = 1.0;
}
_updateWithCurve(_b, tb);
}
}
void _updateWithCurve(Action action, double t) {
if (action is ActionInterval) {
ActionInterval actionInterval = action;
if (actionInterval.curve == null) {
action.update(t);
} else {
action.update(actionInterval.curve.transform(t));
}
} else {
action.update(t);
}
if (t >= 1.0) {
action._finished = true;
}
}
void _finish(Action action) {
action.update(1.0);
action._finished = true;
}
void _reset() {
super._reset();
_a._reset();
_b._reset();
}
}
class ActionGroup extends ActionInterval {
List<Action> _actions;
ActionGroup(this._actions) {
for (Action action in _actions) {
if (action.duration > _duration) {
_duration = action.duration;
}
}
}
void update(double t) {
if (t >= 1.0) {
// Finish all unfinished actions
for (Action action in _actions) {
if (!action._finished) {
action.update(1.0);
action._finished = true;
}
}
} else {
for (Action action in _actions) {
if (action.duration == 0.0) {
// Fire all instant actions immediately
if (!action._finished) {
action.update(1.0);
action._finished = true;
}
} else {
// Update child actions
double ta = (t / (action.duration / duration)).clamp(0.0, 1.0);
if (ta < 1.0) {
if (action is ActionInterval) {
ActionInterval actionInterval = action;
if (actionInterval.curve == null) {
action.update(ta);
} else {
action.update(actionInterval.curve.transform(ta));
}
} else {
action.update(ta);
}
} else if (!action._finished){
action.update(1.0);
action._finished = true;
}
}
}
}
}
void _reset() {
for (Action action in _actions) {
action._reset();
}
}
}
abstract class ActionInstant extends Action {
void step(double dt) {
}
void update(double t) {
fire();
_finished = true;
}
void fire();
}
class ActionCallFunction extends ActionInstant {
ActionCallback _function;
ActionCallFunction(this._function);
void fire() {
_function();
}
}
class ActionRemoveNode extends ActionInstant {
Node _node;
ActionRemoveNode(this._node);
void fire() {
_node.removeFromParent();
}
}
class ActionTween extends ActionInterval {
final Function setter;
final startVal;
final endVal;
var _delta;
ActionTween(this.setter, this.startVal, this.endVal, double duration, [Curve curve]) : super(duration, curve) {
_computeDelta();
}
void _computeDelta() {
if (startVal is Point) {
// Point
double xStart = startVal.x;
double yStart = startVal.y;
double xEnd = endVal.x;
double yEnd = endVal.y;
_delta = new Point(xEnd - xStart, yEnd - yStart);
} else if (startVal is Size) {
// Size
double wStart = startVal.width;
double hStart = startVal.height;
double wEnd = endVal.width;
double hEnd = endVal.height;
_delta = new Size(wEnd - wStart, hEnd - hStart);
} else if (startVal is Rect) {
// Rect
double lStart = startVal.left;
double tStart = startVal.top;
double rStart = startVal.right;
double bStart = startVal.bottom;
double lEnd = endVal.left;
double tEnd = endVal.top;
double rEnd = endVal.right;
double bEnd = endVal.bottom;
_delta = new Rect.fromLTRB(lEnd - lStart, tEnd - tStart, rEnd - rStart, bEnd - bStart);
} else if (startVal is double) {
// Double
_delta = endVal - startVal;
} else if (startVal is Color) {
// Color
int aDelta = endVal.alpha - startVal.alpha;
int rDelta = endVal.red - startVal.red;
int gDelta = endVal.green - startVal.green;
int bDelta = endVal.blue - startVal.blue;
_delta = new _ColorDiff(aDelta, rDelta, gDelta, bDelta);
} else {
assert(false);
}
}
void update(double t) {
var newVal;
if (startVal is Point) {
// Point
double xStart = startVal.x;
double yStart = startVal.y;
double xDelta = _delta.x;
double yDelta = _delta.y;
newVal = new Point(xStart + xDelta * t, yStart + yDelta * t);
} else if (startVal is Size) {
// Size
double wStart = startVal.width;
double hStart = startVal.height;
double wDelta = _delta.width;
double hDelta = _delta.height;
newVal = new Size(wStart + wDelta * t, hStart + hDelta * t);
} else if (startVal is Rect) {
// Rect
double lStart = startVal.left;
double tStart = startVal.top;
double rStart = startVal.right;
double bStart = startVal.bottom;
double lDelta = _delta.left;
double tDelta = _delta.top;
double rDelta = _delta.right;
double bDelta = _delta.bottom;
newVal = new Rect.fromLTRB(lStart + lDelta * t, tStart + tDelta * t, rStart + rDelta * t, bStart + bDelta * t);
} else if (startVal is double) {
// Doubles
newVal = startVal + _delta * t;
} else if (startVal is Color) {
// Colors
int aNew = (startVal.alpha + (_delta.alpha * t).toInt()).clamp(0, 255);
int rNew = (startVal.red + (_delta.red * t).toInt()).clamp(0, 255);
int gNew = (startVal.green + (_delta.green * t).toInt()).clamp(0, 255);
int bNew = (startVal.blue + (_delta.blue * t).toInt()).clamp(0, 255);
newVal = new Color.fromARGB(aNew, rNew, gNew, bNew);
} else {
// Oopses
assert(false);
}
setter(newVal);
}
}
class ActionController {
List<Action> _actions = [];
ActionController();
void run(Action action, [Object tag]) {
assert(!action._added);
action._tag = tag;
action._added = true;
action.update(0.0);
_actions.add(action);
}
void stop(Action action) {
if (_actions.remove(action)) {
action._added = false;
action._reset();
}
}
void _stopAtIndex(int i) {
Action action = _actions[i];
action._added = false;
action._reset();
_actions.removeAt(i);
}
void stopWithTag(Object tag) {
for (int i = _actions.length - 1; i >= 0; i--) {
Action action = _actions[i];
if (action._tag == tag) {
_stopAtIndex(i);
}
}
}
void stopAll() {
for (int i = _actions.length - 1; i >= 0; i--) {
_stopAtIndex(i);
}
}
void step(double dt) {
for (int i = _actions.length - 1; i >= 0; i--) {
Action action = _actions[i];
action.step(dt);
if (action._finished) {
action._added = false;
_actions.removeAt(i);
}
}
}
}
class _ColorDiff {
final int alpha;
final int red;
final int green;
final int blue;
_ColorDiff(this.alpha, this.red, this.green, this.blue);
}
double _bounce(double t)
{
if (t < 1.0 / 2.75) {
return 7.5625 * t * t;
} else if (t < 2 / 2.75) {
t -= 1.5 / 2.75;
return 7.5625 * t * t + 0.75;
} else if (t < 2.5 / 2.75) {
t -= 2.25 / 2.75;
return 7.5625 * t * t + 0.9375;
}
t -= 2.625 / 2.75;
return 7.5625 * t * t + 0.984375;
}
class BounceOutCurve implements Curve {
const BounceOutCurve();
double transform(double t) {
return _bounce(t);
}
}
const BounceOutCurve bounceOut = const BounceOutCurve();

View File

@@ -0,0 +1,82 @@
part of sprites;
class ColorSequence {
List<Color> colors;
List<double> colorStops;
ColorSequence(this.colors, this.colorStops) {
assert(colors != null);
assert(colorStops != null);
assert(colors.length == colorStops.length);
}
ColorSequence.fromStartAndEndColor(Color start, Color end) {
colors = [start, end];
colorStops = [0.0, 1.0];
}
ColorSequence.copy(ColorSequence sequence) {
colors = new List<Color>.from(sequence.colors);
colorStops = new List<double>.from(sequence.colorStops);
}
ColorSequence.copyWithVariance(ColorSequence sequence, int alphaVar, int redVar, int greenVar, int blueVar) {
colors = new List<Color>();
colorStops = new List<double>.from(sequence.colorStops);
math.Random rand = new math.Random();
for (Color color in sequence.colors) {
int aDelta = ((rand.nextDouble() * 2.0 - 1.0) * alphaVar).toInt();
int rDelta = ((rand.nextDouble() * 2.0 - 1.0) * redVar).toInt();
int gDelta = ((rand.nextDouble() * 2.0 - 1.0) * greenVar).toInt();
int bDelta = ((rand.nextDouble() * 2.0 - 1.0) * blueVar).toInt();
int aNew = (color.alpha + aDelta).clamp(0, 255);
int rNew = (color.red + rDelta).clamp(0, 255);
int gNew = (color.green + gDelta).clamp(0, 255);
int bNew = (color.blue + bDelta).clamp(0, 255);
colors.add(new Color.fromARGB(aNew, rNew, gNew, bNew));
}
}
Color colorAtPosition(double pos) {
assert(pos >= 0.0 && pos <= 1.0);
double lastStop = colorStops[0];
Color lastColor = colors[0];
for (int i = 0; i < colors.length; i++) {
double currentStop = colorStops[i];
Color currentColor = colors[i];
if (pos <= currentStop) {
double blend = (pos - lastStop) / (currentStop - lastStop);
return _interpolateColor(lastColor, currentColor, blend);
}
lastStop = currentStop;
lastColor = currentColor;
}
return colors[colors.length-1];
}
}
Color _interpolateColor(Color a, Color b, double blend) {
double aa = a.alpha.toDouble();
double ar = a.red.toDouble();
double ag = a.green.toDouble();
double ab = a.blue.toDouble();
double ba = b.alpha.toDouble();
double br = b.red.toDouble();
double bg = b.green.toDouble();
double bb = b.blue.toDouble();
int na = (aa * (1.0 - blend) + ba * blend).toInt();
int nr = (ar * (1.0 - blend) + br * blend).toInt();
int ng = (ag * (1.0 - blend) + bg * blend).toInt();
int nb = (ab * (1.0 - blend) + bb * blend).toInt();
return new Color.fromARGB(na, nr, ng, nb);
}

View File

@@ -0,0 +1,10 @@
library game;
import 'dart:sky' as sky;
import 'dart:math' as Math;
import 'package:vector_math/vector_math_64.dart';
import 'package:sky/widgets/widget.dart';
import 'sprites.dart';
import 'package:sky/rendering/object.dart';
part 'game_demo_world.dart';

View File

@@ -0,0 +1,629 @@
part of game;
const double _steeringThreshold = 0.0;
const double _steeringMax = 150.0;
// Random generator
Math.Random _rand = new Math.Random();
const double _gameSizeWidth = 1024.0;
const double _gameSizeHeight = 1024.0;
const double _shipRadius = 30.0;
const double _lrgAsteroidRadius = 40.0;
const double _medAsteroidRadius = 20.0;
const double _smlAsteroidRadius = 10.0;
const double _maxAsteroidSpeed = 1.0;
const int _lifeTimeLaser = 50;
const int _numStarsInStarField = 150;
const int _numFramesShieldActive = 60 * 5;
const int _numFramesShieldFlickers = 60;
class GameDemoWorld extends NodeWithSize {
// Images
sky.Image _imgNebula;
SpriteSheet _spriteSheet;
// Inputs
double _joystickX = 0.0;
double _joystickY = 0.0;
Node _gameLayer;
Ship _ship;
Sprite _shield;
List<Asteroid> _asteroids = [];
List<Laser> _lasers = [];
StarField _starField;
Nebula _nebula;
// Game state
int _numFrames = 0;
bool _isGameOver = false;
GameDemoWorld(App app, ImageMap images, this._spriteSheet) : super(new Size(_gameSizeWidth, _gameSizeHeight)) {
// Fetch images
_imgNebula = images["assets/nebula.png"];
_gameLayer = new Node();
this.addChild(_gameLayer);
// Add some asteroids to the game world
for (int i = 0; i < 5; i++) {
addAsteroid(AsteroidSize.large);
}
for (int i = 0; i < 5; i++) {
addAsteroid(AsteroidSize.medium);
}
// Add ship
addShip();
// Add background
Sprite sprtBackground = new Sprite.fromImage(images["assets/starfield.png"]);
sprtBackground.position = new Point(512.0, 512.0);
sprtBackground.zPosition = -3.0;
addChild(sprtBackground);
// Add starfield
_starField = new StarField(_spriteSheet, _numStarsInStarField);
_starField.zPosition = -2.0;
addChild(_starField);
// Add nebula
addNebula();
userInteractionEnabled = true;
handleMultiplePointers = true;
}
// Methods for adding game objects
void addAsteroid(AsteroidSize size, [Point pos]) {
Asteroid asteroid = new Asteroid(_spriteSheet, size);
asteroid.zPosition = 1.0;
if (pos != null) asteroid.position = pos;
_gameLayer.addChild(asteroid);
_asteroids.add(asteroid);
}
void addShip() {
Ship ship = new Ship(_spriteSheet["ship.png"]);
ship.zPosition = 10.0;
_gameLayer.addChild(ship);
_ship = ship;
_shield = new Sprite(_spriteSheet["shield.png"]);
_shield.zPosition = 11.0;
_shield.scale = 0.5;
_shield.transferMode = sky.TransferMode.plus;
_gameLayer.addChild(_shield);
Action rotate = new ActionRepeatForever(new ActionTween((a) => _shield.rotation = a, 0.0, 360.0, 1.0));
actions.run(rotate);
}
void addLaser() {
Laser laser = new Laser(_spriteSheet["laser.png"], _ship);
laser.zPosition = 8.0;
laser.constrainProportions = true;
_lasers.add(laser);
_gameLayer.addChild(laser);
}
void addNebula() {
_nebula = new Nebula.withImage(_imgNebula);
_gameLayer.addChild(_nebula);
}
void addExplosion(AsteroidSize asteroidSize, Point position) {
Node explosionNode = new Node();
// Add particles
ParticleSystem particlesDebris = new ParticleSystem(
_spriteSheet["explosion_particle.png"],
rotateToMovement: true,
startRotation:90.0,
startRotationVar: 0.0,
endRotation: 90.0,
startSize: 0.3,
startSizeVar: 0.1,
endSize: 0.3,
endSizeVar: 0.1,
numParticlesToEmit: 25,
emissionRate:1000.0,
greenVar: 127,
redVar: 127
);
particlesDebris.zPosition = 1010.0;
explosionNode.addChild(particlesDebris);
ParticleSystem particlesFire = new ParticleSystem(
_spriteSheet["fire_particle.png"],
colorSequence: new ColorSequence([new Color(0xffffff33), new Color(0xffff3333), new Color(0x00ff3333)], [0.0, 0.5, 1.0]),
numParticlesToEmit: 25,
emissionRate: 1000.0,
startSize: 0.5,
startSizeVar: 0.1,
endSize: 0.5,
endSizeVar: 0.1,
posVar: new Point(10.0, 10.0),
speed: 10.0,
speedVar: 5.0
);
particlesFire.zPosition = 1011.0;
explosionNode.addChild(particlesFire);
// Add ring
Sprite sprtRing = new Sprite(_spriteSheet["explosion_ring.png"]);
sprtRing.transferMode = sky.TransferMode.plus;
explosionNode.addChild(sprtRing);
Action scale = new ActionTween( (a) => sprtRing.scale = a, 0.2, 1.0, 1.5);
Action scaleAndRemove = new ActionSequence([scale, new ActionRemoveNode(sprtRing)]);
Action fade = new ActionTween( (a) => sprtRing.opacity = a, 1.0, 0.0, 1.5);
actions.run(scaleAndRemove);
actions.run(fade);
// Add streaks
for (int i = 0; i < 5; i++) {
Sprite sprtFlare = new Sprite(_spriteSheet["explosion_flare.png"]);
sprtFlare.pivot = new Point(0.3, 1.0);
sprtFlare.scaleX = 0.3;
sprtFlare.transferMode = sky.TransferMode.plus;
sprtFlare.rotation = _rand.nextDouble() * 360.0;
explosionNode.addChild(sprtFlare);
double multiplier = _rand.nextDouble() * 0.3 + 1.0;
Action scale = new ActionTween( (a) => sprtFlare.scaleY = a, 0.3 * multiplier, 0.8, 1.5 * multiplier);
Action scaleAndRemove = new ActionSequence([scale, new ActionRemoveNode(sprtFlare)]);
Action fadeIn = new ActionTween( (a) => sprtFlare.opacity = a, 0.0, 1.0, 0.5 * multiplier);
Action fadeOut = new ActionTween( (a) => sprtFlare.opacity = a, 1.0, 0.0, 1.0 * multiplier);
Action fadeInOut = new ActionSequence([fadeIn, fadeOut]);
actions.run(scaleAndRemove);
actions.run(fadeInOut);
}
explosionNode.position = position;
explosionNode.zPosition = 1010.0;
if (asteroidSize == AsteroidSize.large) {
explosionNode.scale = 1.5;
}
_gameLayer.addChild(explosionNode);
}
void update(double dt) {
// Move asteroids
for (Asteroid asteroid in _asteroids) {
asteroid.position = pointAdd(asteroid.position, asteroid._movementVector);
}
// Move lasers and remove expired lasers
for (int i = _lasers.length - 1; i >= 0; i--) {
Laser laser = _lasers[i];
laser.move();
if (laser._frameCount > _lifeTimeLaser) {
laser.removeFromParent();
_lasers.removeAt(i);
}
}
// Apply thrust to ship
if (_joystickX != 0.0 || _joystickY != 0.0) {
_ship.thrust(_joystickX, _joystickY);
}
// Move ship
_ship.move();
_shield.position = _ship.position;
// Check collisions between asteroids and lasers
for (int i = _lasers.length -1; i >= 0; i--) {
// Iterate over all the lasers
Laser laser = _lasers[i];
for (int j = _asteroids.length - 1; j >= 0; j--) {
// Iterate over all the asteroids
Asteroid asteroid = _asteroids[j];
// Check for collision
if (pointQuickDist(laser.position, asteroid.position) < laser.radius + asteroid.radius) {
// Remove laser
laser.removeFromParent();
_lasers.removeAt(i);
// Add asteroids and explosions
if (asteroid._asteroidSize == AsteroidSize.large) {
for (int a = 0; a < 3; a++) addAsteroid(AsteroidSize.medium, asteroid.position);
}
else if (asteroid._asteroidSize == AsteroidSize.medium) {
for (int a = 0; a < 5; a++) addAsteroid(AsteroidSize.small, asteroid.position);
}
addExplosion(asteroid._asteroidSize, asteroid.position);
// Remove asteroid
asteroid.removeFromParent();
_asteroids.removeAt(j);
break;
}
}
}
// Check collisions between asteroids and ship
if (_numFrames > _numFramesShieldActive) {
// Shield is no longer active
for (int i = _asteroids.length - 1; i >= 0; i--) {
// Iterate over all the asteroids
Asteroid asteroid = _asteroids[i];
if (pointQuickDist(asteroid.position, _ship.position) < asteroid.radius + _ship.radius) {
killShip();
}
}
}
// Move objects to center camera and warp objects around the edges
centerCamera();
warpObjects();
// Update shield
if (_numFrames > _numFramesShieldActive) _shield.visible = false;
else if (_numFrames > _numFramesShieldActive - _numFramesShieldFlickers) _shield.visible = !_shield.visible;
_numFrames++;
}
void centerCamera() {
const cameraDampening = 0.1;
Point delta = new Point(_gameSizeWidth/2 - _ship.position.x, _gameSizeHeight/2 - _ship.position.y);
delta = pointMult(delta, cameraDampening);
for (Node child in _gameLayer.children) {
child.position = pointAdd(child.position, delta);
}
// Update starfield
_starField.move(delta.x, delta.y);
}
void warpObjects() {
for (Node child in _gameLayer.children) {
if (child.position.x < 0) child.position = pointAdd(child.position, new Point(_gameSizeWidth, 0.0));
if (child.position.x >= _gameSizeWidth) child.position = pointAdd(child.position, new Point(-_gameSizeWidth, 0.0));
if (child.position.y < 0) child.position = pointAdd(child.position, new Point(0.0, _gameSizeHeight));
if (child.position.y >= _gameSizeHeight) child.position = pointAdd(child.position, new Point(0.0, -_gameSizeHeight));
}
}
void killShip() {
if (_isGameOver) return;
// Set game over
_isGameOver = true;
// Remove the ship
_ship.visible = false;
// Add an explosion
addExplosion(AsteroidSize.large, _ship.position);
}
// Handling controls
void controlSteering(double x, double y) {
// Reset controls if it's game over
if (_isGameOver) {
x = y = 0.0;
}
_joystickX = x;
_joystickY = y;
}
void controlFire() {
// Don't shoot if it's game over
if (_isGameOver) return;
addLaser();
}
// Handle pointer events
int _firstPointer = -1;
int _secondPointer = -1;
Point _firstPointerDownPos;
bool handleEvent(SpriteBoxEvent event) {
Point pointerPos = convertPointToNodeSpace(event.boxPosition);
int pointer = event.pointer;
switch (event.type) {
case 'pointerdown':
if (_firstPointer == -1) {
// Assign the first pointer
_firstPointer = pointer;
_firstPointerDownPos = pointerPos;
}
else if (_secondPointer == -1) {
// Assign second pointer
_secondPointer = pointer;
controlFire();
}
else {
// There is a pointer used for steering, let's fire instead
controlFire();
}
break;
case 'pointermove':
if (pointer == _firstPointer) {
// Handle turning control
double joystickX = 0.0;
double deltaX = pointerPos.x - _firstPointerDownPos.x;
if (deltaX > _steeringThreshold || deltaX < -_steeringThreshold) {
joystickX = (deltaX - _steeringThreshold)/(_steeringMax - _steeringThreshold);
if (joystickX > 1.0) joystickX = 1.0;
if (joystickX < -1.0) joystickX = -1.0;
}
double joystickY = 0.0;
double deltaY = pointerPos.y - _firstPointerDownPos.y;
if (deltaY > _steeringThreshold || deltaY < -_steeringThreshold) {
joystickY = (deltaY - _steeringThreshold)/(_steeringMax - _steeringThreshold);
if (joystickY > 1.0) joystickY = 1.0;
if (joystickY < -1.0) joystickY = -1.0;
}
controlSteering(joystickX, joystickY);
}
break;
case 'pointerup':
case 'pointercancel':
if (pointer == _firstPointer) {
// Un-assign the first pointer
_firstPointer = -1;
_firstPointerDownPos = null;
controlSteering(0.0, 0.0);
}
else if (pointer == _secondPointer) {
_secondPointer = -1;
}
break;
default:
break;
}
return true;
}
}
// Game objects
enum AsteroidSize {
small,
medium,
large,
}
class Asteroid extends Sprite {
Point _movementVector;
AsteroidSize _asteroidSize;
double _radius;
double get radius {
if (_radius != null) return _radius;
if (_asteroidSize == AsteroidSize.small) _radius = _smlAsteroidRadius;
else if (_asteroidSize == AsteroidSize.medium) _radius = _medAsteroidRadius;
else if (_asteroidSize == AsteroidSize.large) _radius = _lrgAsteroidRadius;
return _radius;
}
Asteroid(SpriteSheet spriteSheet, AsteroidSize this._asteroidSize) {
size = new Size(radius * 2.0, radius * 2.0);
position = new Point(_gameSizeWidth * _rand.nextDouble(), _gameSizeHeight * _rand.nextDouble());
rotation = 360.0 * _rand.nextDouble();
if (_asteroidSize == AsteroidSize.small) {
texture = spriteSheet["asteroid_small_${_rand.nextInt(2)}.png"];
} else {
texture = spriteSheet["asteroid_big_${_rand.nextInt(2)}.png"];
}
_movementVector = new Point(_rand.nextDouble() * _maxAsteroidSpeed * 2 - _maxAsteroidSpeed,
_rand.nextDouble() * _maxAsteroidSpeed * 2 - _maxAsteroidSpeed);
userInteractionEnabled = true;
// Rotate forever
double direction = (_rand.nextBool()) ? 360.0 : -360.0;
ActionTween rot = new ActionTween( (a) => rotation = a, 0.0, direction, 2.0 * _rand.nextDouble() + 2.0);
ActionRepeatForever repeat = new ActionRepeatForever(rot);
actions.run(repeat);
}
bool handleEvent(SpriteBoxEvent event) {
if (event.type == "pointerdown") {
actions.stopWithTag("fade");
colorOverlay = new Color(0x99ffffff);
}
else if (event.type == "pointerup") {
// Fade out the color overlay
Action fadeOut = new ActionTween((a) => this.colorOverlay = a, new Color(0x99ffffff), new Color(0x00ffffff), 1.0);
Action fadeOutAndRemove = new ActionSequence([fadeOut, new ActionCallFunction(() => this.colorOverlay = null)]);
actions.run(fadeOutAndRemove, "fade");
}
return false;
}
}
class Ship extends Sprite {
Vector2 _movementVector;
double _rotationTarget;
double radius = _shipRadius;
Ship(Texture img) : super(img) {
_movementVector = new Vector2.zero();
rotation = _rotationTarget = 270.0;
// Create sprite
size = new Size(_shipRadius * 2.0, _shipRadius * 2.0);
position = new Point(_gameSizeWidth/2.0, _gameSizeHeight/2.0);
}
void thrust(double x, double y) {
_rotationTarget = convertRadians2Degrees(Math.atan2(y, x));
Vector2 directionVector = new Vector2(x, y).normalize();
_movementVector.addScaled(directionVector, 1.0);
}
void move() {
position = new Point(position.x + _movementVector[0], position.y + _movementVector[1]);
_movementVector.scale(0.9);
rotation = dampenRotation(rotation, _rotationTarget, 0.1);
}
}
class Laser extends Sprite {
int _frameCount = 0;
Point _movementVector;
double radius = 20.0;
Laser(Texture img, Ship ship) : super(img) {
size = new Size(30.0, 30.0);
position = ship.position;
rotation = ship.rotation + 90.0;
transferMode = sky.TransferMode.plus;
double rotRadians = convertDegrees2Radians(rotation);
_movementVector = pointMult(new Point(Math.sin(rotRadians), -Math.cos(rotRadians)), 10.0);
_movementVector = new Point(_movementVector.x + ship._movementVector[0], _movementVector.y + ship._movementVector[1]);
}
void move() {
position = pointAdd(position, _movementVector);
_frameCount++;
}
}
// Background starfield
class StarField extends Node {
int _numStars;
List<Point> _starPositions;
List<double> _starScales;
List<double> _opacity;
List<Texture> _textures;
StarField(SpriteSheet spriteSheet, this._numStars) {
_starPositions = [];
_starScales = [];
_opacity = [];
_textures = [];
for (int i = 0; i < _numStars; i++) {
_starPositions.add(new Point(_rand.nextDouble() * _gameSizeWidth, _rand.nextDouble() * _gameSizeHeight));
_starScales.add(_rand.nextDouble());
_opacity.add(_rand.nextDouble() * 0.5 + 0.5);
_textures.add(spriteSheet["star_${_rand.nextInt(2)}.png"]);
}
}
void paint(PaintingCanvas canvas) {
// Setup paint object for opacity and transfer mode
Paint paint = new Paint();
paint.setTransferMode(sky.TransferMode.plus);
double baseScaleX = 64.0 / _textures[0].size.width;
double baseScaleY = 64.0 / _textures[0].size.height;
// Draw each star
for (int i = 0; i < _numStars; i++) {
Point pos = _starPositions[i];
double scale = _starScales[i];
paint.color = new Color.fromARGB((255.0*_opacity[i]).toInt(), 255, 255, 255);
canvas.save();
canvas.translate(pos.x, pos.y);
canvas.scale(baseScaleX * scale, baseScaleY * scale);
canvas.drawImageRect(_textures[i].image, _textures[i].frame, _textures[i].spriteSourceSize, paint);
canvas.restore();
}
}
void move(double dx, double dy) {
for (int i = 0; i < _numStars; i++) {
double xPos = _starPositions[i].x;
double yPos = _starPositions[i].y;
double scale = _starScales[i];
xPos += dx * scale;
yPos += dy * scale;
if (xPos >= _gameSizeWidth) xPos -= _gameSizeWidth;
if (xPos < 0) xPos += _gameSizeWidth;
if (yPos >= _gameSizeHeight) yPos -= _gameSizeHeight;
if (yPos < 0) yPos += _gameSizeHeight;
_starPositions[i] = new Point(xPos, yPos);
}
}
}
class Nebula extends Node {
Nebula.withImage(sky.Image img) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
Sprite sprt = new Sprite.fromImage(img);
sprt.pivot = Point.origin;
sprt.position = new Point(i * _gameSizeWidth - _gameSizeWidth, j * _gameSizeHeight - _gameSizeHeight);
addChild(sprt);
}
}
}
}
// Convenience methods
Point pointAdd(Point a, Point b) {
return new Point(a.x+ b.x, a.y + b.y);
}
Point pointMult(Point a, double multiplier) {
return new Point(a.x * multiplier, a.y * multiplier);
}
double dampenRotation(double src, double dst, double dampening) {
double delta = dst - src;
while (delta > 180.0) delta -= 360;
while (delta < -180) delta += 360;
delta *= dampening;
return src + delta;
}
double pointQuickDist(Point a, Point b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
if (dx < 0.0) dx = -dx;
if (dy < 0.0) dy = -dy;
if (dx > dy) {
return dx + dy/2.0;
}
else {
return dy + dx/2.0;
}
}

View File

@@ -0,0 +1,25 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of sprites;
class ImageMap {
ImageMap(AssetBundle bundle) : _bundle = bundle;
final AssetBundle _bundle;
final Map<String, Image> _images = new Map<String, Image>();
Future<List<Image>> load(List<String> urls) {
return Future.wait(urls.map(_loadImage));
}
Future<Image> _loadImage(String url) async {
Image image = await _bundle.loadImage(url);
_images[url] = image;
return image;
}
Image getImage(String url) => _images[url];
Image operator [](String url) => _images[url];
}

View File

@@ -0,0 +1,539 @@
part of sprites;
double convertDegrees2Radians(double degrees) => degrees * math.PI/180.8;
double convertRadians2Degrees(double radians) => radians * 180.0/math.PI;
/// A base class for all objects that can be added to the sprite node tree and rendered to screen using [SpriteBox] and
/// [SpriteWidget].
///
/// The [Node] class itself doesn't render any content, but provides the basic functions of any type of node, such as
/// handling transformations and user input. To render the node tree, a root node must be added to a [SpriteBox] or a
/// [SpriteWidget]. Commonly used sub-classes of [Node] are [Sprite], [NodeWithSize], and many more upcoming subclasses.
///
/// Nodes form a hierarchical tree. Each node can have a number of children, and the transformation (positioning,
/// rotation, and scaling) of a node also affects its children.
class Node {
// Member variables
SpriteBox _spriteBox;
Node _parent;
Point _position = Point.origin;
double _rotation = 0.0;
Matrix4 _transformMatrix = new Matrix4.identity();
Matrix4 _transformMatrixNodeToBox;
Matrix4 _transformMatrixBoxToNode;
double _scaleX = 1.0;
double _scaleY = 1.0;
/// The visibility of this node and its children.
bool visible = true;
double _zPosition = 0.0;
int _addedOrder;
int _childrenLastAddedOrder = 0;
bool _childrenNeedSorting = false;
/// Decides if the node and its children is currently paused.
///
/// A paused node will not receive any input events, update calls, or run any animations.
///
/// myNodeTree.paused = true;
bool paused = false;
bool _userInteractionEnabled = false;
/// If set to true the node will receive multiple pointers, otherwise it will only receive events the first pointer.
///
/// This property is only meaningful if [userInteractionEnabled] is set to true. Default value is false.
///
/// class MyCustomNode extends Node {
/// handleMultiplePointers = true;
/// }
bool handleMultiplePointers = false;
int _handlingPointer;
List<Node>_children = [];
ActionController _actions;
ActionController get actions {
if (_actions == null) {
_actions = new ActionController();
}
return _actions;
}
// Constructors
/// Creates a new [Node] without any transformation.
///
/// var myNode = new Node();
Node() {
}
// Property setters and getters
/// The [SpriteBox] this node is added to, or null if it's not currently added to a [SpriteBox].
///
/// For most applications it's not necessary to access the [SpriteBox] directly.
///
/// // Get the transformMode of the sprite box
/// var transformMode = myNode.spriteBox.transformMode;
SpriteBox get spriteBox => _spriteBox;
/// The parent of this node, or null if it doesn't have a parent.
///
/// // Hide the parent
/// myNode.parent.visible = false;
Node get parent => _parent;
/// The rotation of this node in degrees.
///
/// myNode.rotation = 45.0;
double get rotation => _rotation;
void set rotation(double rotation) {
assert(rotation != null);
_rotation = rotation;
_invalidateTransformMatrix();
}
/// The position of this node relative to its parent.
///
/// myNode.position = new Point(42.0, 42.0);
Point get position => _position;
void set position(Point position) {
assert(position != null);
_position = position;
_invalidateTransformMatrix();
}
/// The draw order of this node compared to its parent and its siblings.
///
/// By default nodes are drawn in the order that they have been added to a parent. To override this behavior the
/// [zPosition] property can be used. A higher value of this property will force the node to be drawn in front of
/// siblings that have a lower value. If a negative value is used the node will be drawn behind its parent.
///
/// nodeInFront.zPosition = 1.0;
/// nodeBehind.zPosition = -1.0;
double get zPosition => _zPosition;
void set zPosition(double zPosition) {
assert(zPosition != null);
_zPosition = zPosition;
if (_parent != null) {
_parent._childrenNeedSorting = true;
}
}
/// The scale of this node relative its parent.
///
/// The [scale] property is only valid if [scaleX] and [scaleY] are equal values.
///
/// myNode.scale = 5.0;
double get scale {
assert(_scaleX == _scaleY);
return _scaleX;
}
void set scale(double scale) {
assert(scale != null);
_scaleX = _scaleY = scale;
_invalidateTransformMatrix();
}
/// The horizontal scale of this node relative its parent.
///
/// myNode.scaleX = 5.0;
double get scaleX => _scaleX;
void set scaleX(double scaleX) {
assert(scaleX != null);
_scaleX = scaleX;
_invalidateTransformMatrix();
}
/// The vertical scale of this node relative its parent.
///
/// myNode.scaleY = 5.0;
double get scaleY => _scaleY;
void set scaleY(double scaleY) {
assert(scaleY != null);
_scaleY = scaleY;
_invalidateTransformMatrix();
}
/// A list of the children of this node.
///
/// This list should only be modified by using the [addChild] and [removeChild] methods.
///
/// // Iterate over a nodes children
/// for (Node child in myNode.children) {
/// // Do something with the child
/// }
List<Node> get children {
_sortChildren();
return _children;
}
// Adding and removing children
/// Adds a child to this node.
///
/// The same node cannot be added to multiple nodes.
///
/// addChild(new Sprite(myImage));
void addChild(Node child) {
assert(child != null);
assert(child._parent == null);
_childrenNeedSorting = true;
_children.add(child);
child._parent = this;
child._spriteBox = this._spriteBox;
_childrenLastAddedOrder += 1;
child._addedOrder = _childrenLastAddedOrder;
if (_spriteBox != null) _spriteBox._eventTargets = null;
}
/// Removes a child from this node.
///
/// removeChild(myChildNode);
void removeChild(Node child) {
assert(child != null);
if (_children.remove(child)) {
child._parent = null;
child._spriteBox = null;
if (_spriteBox != null) _spriteBox._eventTargets = null;
}
}
/// Removes this node from its parent node.
///
/// removeFromParent();
void removeFromParent() {
assert(_parent != null);
_parent.removeChild(this);
}
/// Removes all children of this node.
///
/// removeAllChildren();
void removeAllChildren() {
for (Node child in _children) {
child._parent = null;
child._spriteBox = null;
}
_children = [];
_childrenNeedSorting = false;
if (_spriteBox != null) _spriteBox._eventTargets = null;
}
void _sortChildren() {
// Sort children primarily by zPosition, secondarily by added order
if (_childrenNeedSorting) {
_children.sort((Node a, Node b) {
if (a._zPosition == b._zPosition) {
return a._addedOrder - b._addedOrder;
}
else if (a._zPosition > b._zPosition) {
return 1;
}
else {
return -1;
}
});
_childrenNeedSorting = false;
}
}
// Calculating the transformation matrix
/// The transformMatrix describes the transformation from the node's parent.
///
/// You cannot set the transformMatrix directly, instead use the position, rotation and scale properties.
///
/// Matrix4 matrix = myNode.transformMatrix;
Matrix4 get transformMatrix {
if (_transformMatrix != null) {
return _transformMatrix;
}
double cx, sx, cy, sy;
if (_rotation == 0.0) {
cx = 1.0;
sx = 0.0;
cy = 1.0;
sy = 0.0;
}
else {
double radiansX = convertDegrees2Radians(_rotation);
double radiansY = convertDegrees2Radians(_rotation);
cx = math.cos(radiansX);
sx = math.sin(radiansX);
cy = math.cos(radiansY);
sy = math.sin(radiansY);
}
// Create transformation matrix for scale, position and rotation
_transformMatrix = new Matrix4(cy * _scaleX, sy * _scaleX, 0.0, 0.0,
-sx * _scaleY, cx * _scaleY, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
_position.x, _position.y, 0.0, 1.0);
return _transformMatrix;
}
void _invalidateTransformMatrix() {
_transformMatrix = null;
_invalidateToBoxTransformMatrix();
}
void _invalidateToBoxTransformMatrix () {
_transformMatrixNodeToBox = null;
_transformMatrixBoxToNode = null;
for (Node child in children) {
child._invalidateToBoxTransformMatrix();
}
}
// Transforms to other nodes
Matrix4 _nodeToBoxMatrix() {
assert(_spriteBox != null);
if (_transformMatrixNodeToBox != null) {
return _transformMatrixNodeToBox;
}
if (_parent == null) {
// Base case, we are at the top
assert(this == _spriteBox.rootNode);
_transformMatrixNodeToBox = new Matrix4.copy(_spriteBox.transformMatrix).multiply(transformMatrix);
}
else {
_transformMatrixNodeToBox = new Matrix4.copy(_parent._nodeToBoxMatrix()).multiply(transformMatrix);
}
return _transformMatrixNodeToBox;
}
Matrix4 _boxToNodeMatrix() {
assert(_spriteBox != null);
if (_transformMatrixBoxToNode != null) {
return _transformMatrixBoxToNode;
}
_transformMatrixBoxToNode = new Matrix4.copy(_nodeToBoxMatrix());
_transformMatrixBoxToNode.invert();
return _transformMatrixBoxToNode;
}
/// Converts a point from the coordinate system of the [SpriteBox] to the local coordinate system of the node.
///
/// This method is particularly useful when handling pointer events and need the pointers position in a local
/// coordinate space.
///
/// Point localPoint = myNode.convertPointToNodeSpace(pointInBoxCoordinates);
Point convertPointToNodeSpace(Point boxPoint) {
assert(boxPoint != null);
assert(_spriteBox != null);
Vector4 v =_boxToNodeMatrix().transform(new Vector4(boxPoint.x, boxPoint.y, 0.0, 1.0));
return new Point(v[0], v[1]);
}
/// Converts a point from the local coordinate system of the node to the coordinate system of the [SpriteBox].
///
/// Point pointInBoxCoordinates = myNode.convertPointToBoxSpace(localPoint);
Point convertPointToBoxSpace(Point nodePoint) {
assert(nodePoint != null);
assert(_spriteBox != null);
Vector4 v =_nodeToBoxMatrix().transform(new Vector4(nodePoint.x, nodePoint.y, 0.0, 1.0));
return new Point(v[0], v[1]);
}
/// Converts a [point] from another [node]s coordinate system into the local coordinate system of this node.
///
/// Point pointInNodeASpace = nodeA.convertPointFromNode(pointInNodeBSpace, nodeB);
Point convertPointFromNode(Point point, Node node) {
assert(node != null);
assert(point != null);
assert(_spriteBox != null);
assert(_spriteBox == node._spriteBox);
Point boxPoint = node.convertPointToBoxSpace(point);
Point localPoint = convertPointToNodeSpace(boxPoint);
return localPoint;
}
// Hit test
/// Returns true if the [point] is inside the node, the [point] is in the local coordinate system of the node.
///
/// myNode.isPointInside(localPoint);
///
/// [NodeWithSize] provides a basic bounding box check for this method, if you require a more detailed check this
/// method can be overridden.
///
/// bool isPointInside (Point nodePoint) {
/// double minX = -size.width * pivot.x;
/// double minY = -size.height * pivot.y;
/// double maxX = minX + size.width;
/// double maxY = minY + size.height;
/// return (nodePoint.x >= minX && nodePoint.x < maxX &&
/// nodePoint.y >= minY && nodePoint.y < maxY);
/// }
bool isPointInside(Point point) {
assert(point != null);
return false;
}
// Rendering
void _visit(PaintingCanvas canvas) {
assert(canvas != null);
if (!visible) return;
_prePaint(canvas);
_visitChildren(canvas);
_postPaint(canvas);
}
void _prePaint(PaintingCanvas canvas) {
canvas.save();
// Get the transformation matrix and apply transform
canvas.concat(transformMatrix.storage);
}
/// Paints this node to the canvas.
///
/// Subclasses, such as [Sprite], override this method to do the actual painting of the node. To do custom
/// drawing override this method and make calls to the [canvas] object. All drawing is done in the node's local
/// coordinate system, relative to the node's position. If you want to make the drawing relative to the node's
/// bounding box's origin, override [NodeWithSize] and call the applyTransformForPivot method before making calls for
/// drawing.
///
/// void paint(PaintingCanvas canvas) {
/// canvas.save();
/// applyTransformForPivot(canvas);
///
/// // Do painting here
///
/// canvas.restore();
/// }
void paint(PaintingCanvas canvas) {
}
void _visitChildren(PaintingCanvas canvas) {
// Sort children if needed
_sortChildren();
int i = 0;
// Visit children behind this node
while (i < _children.length) {
Node child = _children[i];
if (child.zPosition >= 0.0) break;
child._visit(canvas);
i++;
}
// Paint this node
paint(canvas);
// Visit children in front of this node
while (i < _children.length) {
Node child = _children[i];
child._visit(canvas);
i++;
}
}
void _postPaint(PaintingCanvas canvas) {
canvas.restore();
}
// Receiving update calls
/// Called before a frame is drawn.
///
/// Override this method to do any updates to the node or node tree before it's drawn to screen.
///
/// // Make the node rotate at a fixed speed
/// void update(double dt) {
/// rotation = rotation * 10.0 * dt;
/// }
void update(double dt) {
}
/// Called whenever the [SpriteBox] is modified or resized, or if the device is rotated.
///
/// Override this method to do any updates that may be necessary to correctly display the node or node tree with the
/// new layout of the [SpriteBox].
///
/// void spriteBoxPerformedLayout() {
/// // Move some stuff around here
/// }
void spriteBoxPerformedLayout() {
}
// Handling user interaction
/// The node will receive user interactions, such as pointer (touch or mouse) events.
///
/// class MyCustomNode extends NodeWithSize {
/// userInteractionEnabled = true;
/// }
bool get userInteractionEnabled => _userInteractionEnabled;
void set userInteractionEnabled(bool userInteractionEnabled) {
_userInteractionEnabled = userInteractionEnabled;
if (_spriteBox != null) _spriteBox._eventTargets = null;
}
/// Handles an event, such as a pointer (touch or mouse) event.
///
/// Override this method to handle events. The node will only receive events if the [userInteractionEnabled] property
/// is set to true and the [isPointInside] method returns true for the position of the pointer down event (default
/// behavior provided by [NodeWithSize]). Unless [handleMultiplePointers] is set to true, the node will only receive
/// events for the first pointer that is down.
///
/// Return true if the node has consumed the event, if an event is consumed it will not be passed on to nodes behind
/// the current node.
///
/// // MyTouchySprite gets transparent when we touch it
/// class MyTouchySprite extends Sprite {
///
/// MyTouchySprite(Image img) : super (img) {
/// userInteractionEnabled = true;
/// }
///
/// bool handleEvent(SpriteBoxEvent event) {
/// if (event.type == 'pointerdown) {
/// opacity = 0.5;
/// }
/// else if (event.type == 'pointerup') {
/// opacity = 1.0;
/// }
/// return true;
/// }
/// }
bool handleEvent(SpriteBoxEvent event) {
return false;
}
}

View File

@@ -0,0 +1,60 @@
part of sprites;
/// The super class of any [Node] that has a size.
///
/// NodeWithSize adds the ability for a node to have a size and a pivot point.
class NodeWithSize extends Node {
/// Changing the size will affect the size of the rendering of the node.
///
/// myNode.size = new Size(1024.0, 1024.0);
Size size;
/// The normalized point which the node is transformed around.
///
/// // Position myNode from is middle top
/// myNode.pivot = new Point(0.5, 0.0);
Point pivot;
/// Creates a new NodeWithSize.
///
/// The default [size] is zero and the default [pivot] point is the origin. Subclasses may change the default values.
///
/// var myNodeWithSize = new NodeWithSize(new Size(1024.0, 1024.0));
NodeWithSize([Size this.size, Point this.pivot]) {
if (size == null) size = Size.zero;
if (pivot == null) pivot = Point.origin;
}
/// Call this method in your [paint] method if you want the origin of your drawing to be the top left corner of the
/// node's bounding box.
///
/// If you use this method you will need to save and restore your canvas at the beginning and
/// end of your [paint] method.
///
/// void paint(PaintingCanvas canvas) {
/// canvas.save();
/// applyTransformForPivot(canvas);
///
/// // Do painting here
///
/// canvas.restore();
/// }
void applyTransformForPivot(PaintingCanvas canvas) {
if (pivot.x != 0 || pivot.y != 0) {
double pivotInPointsX = size.width * pivot.x;
double pivotInPointsY = size.height * pivot.y;
canvas.translate(-pivotInPointsX, -pivotInPointsY);
}
}
bool isPointInside (Point nodePoint) {
double minX = -size.width * pivot.x;
double minY = -size.height * pivot.y;
double maxX = minX + size.width;
double maxY = minY + size.height;
return (nodePoint.x >= minX && nodePoint.x < maxX &&
nodePoint.y >= minY && nodePoint.y < maxY);
}
}

View File

@@ -0,0 +1,320 @@
part of sprites;
class _Particle {
Vector2 pos;
Vector2 startPos;
double colorPos;
double deltaColorPos;
double size;
double deltaSize;
double rotation;
double deltaRotation;
double timeToLive;
Vector2 dir;
double radialAccel;
double tangentialAccel;
ColorSequence colorSequence;
}
class ParticleSystem extends Node {
Texture texture;
double life;
double lifeVar;
Point posVar;
double startSize;
double startSizeVar;
double endSize;
double endSizeVar;
double startRotation;
double startRotationVar;
double endRotation;
double endRotationVar;
bool rotateToMovement;
double direction;
double directionVar;
double speed;
double speedVar;
double radialAcceleration;
double radialAccelerationVar;
double tangentialAcceleration;
double tangentialAccelerationVar;
Vector2 gravity;
int maxParticles;
int numParticlesToEmit;
double emissionRate;
bool autoRemoveOnFinish;
ColorSequence colorSequence;
int alphaVar;
int redVar;
int greenVar;
int blueVar;
TransferMode colorTransferMode;
TransferMode transferMode;
List<_Particle> _particles;
double _emitCounter;
// Not yet used:
// double _elapsedTime;
int _numEmittedParticles = 0;
math.Random _rand;
ParticleSystem(this.texture,
{this.life: 1.5,
this.lifeVar: 1.0,
this.posVar: Point.origin,
this.startSize: 2.5,
this.startSizeVar: 0.5,
this.endSize: 0.0,
this.endSizeVar: 0.0,
this.startRotation: 0.0,
this.startRotationVar: 0.0,
this.endRotation: 0.0,
this.endRotationVar: 0.0,
this.rotateToMovement : false,
this.direction: 0.0,
this.directionVar: 360.0,
this.speed: 100.0,
this.speedVar: 50.0,
this.radialAcceleration: 0.0,
this.radialAccelerationVar: 0.0,
this.tangentialAcceleration: 0.0,
this.tangentialAccelerationVar: 0.0,
this.gravity,
this.maxParticles: 100,
this.emissionRate: 50.0,
this.colorSequence,
this.alphaVar: 0,
this.redVar: 0,
this.greenVar: 0,
this.blueVar: 0,
this.colorTransferMode: TransferMode.multiply,
this.transferMode: TransferMode.plus,
this.numParticlesToEmit: 0,
this.autoRemoveOnFinish: true}) {
_particles = new List<_Particle>();
_rand = new math.Random();
_emitCounter = 0.0;
// _elapsedTime = 0.0;
if (gravity == null) gravity = new Vector2.zero();
if (colorSequence == null) colorSequence = new ColorSequence.fromStartAndEndColor(new Color(0xffffffff), new Color(0x00ffffff));
}
void update(double dt) {
// Create new particles
double rate = 1.0 / emissionRate;
if (_particles.length < maxParticles) {
_emitCounter += dt;
}
while(_particles.length < maxParticles
&& _emitCounter > rate
&& (numParticlesToEmit == 0 || _numEmittedParticles < numParticlesToEmit)) {
// Add a new particle
_addParticle();
_emitCounter -= rate;
}
// _elapsedTime += dt;
// Iterate over all particles
for (int i = _particles.length -1; i >= 0; i--) {
_Particle particle = _particles[i];
// Manage life time
particle.timeToLive -= dt;
if (particle.timeToLive <= 0) {
_particles.removeAt(i);
continue;
}
// Update the particle
// Radial acceleration
Vector2 radial;
if (particle.pos[0] != 0 || particle.pos[1] != 0) {
radial = new Vector2.copy(particle.pos).normalize();
} else {
radial = new Vector2.zero();
}
Vector2 tangential = new Vector2.copy(radial);
radial.scale(particle.radialAccel);
// Tangential acceleration
double newY = tangential.x;
tangential.x = -tangential.y;
tangential.y = newY;
tangential.scale(particle.tangentialAccel);
// (gravity + radial + tangential) * dt
Vector2 accel = (gravity + radial + tangential).scale(dt);
particle.dir += accel;
particle.pos += new Vector2.copy(particle.dir).scale(dt);
// Size
particle.size = math.max(particle.size + particle.deltaSize * dt, 0.0);
// Angle
particle.rotation += particle.deltaRotation * dt;
// Color
particle.colorPos = math.min(particle.colorPos + particle.deltaColorPos * dt, 1.0);
}
if (autoRemoveOnFinish && _particles.length == 0 && _numEmittedParticles > 0) {
if (parent != null) removeFromParent();
}
}
void _addParticle() {
_Particle particle = new _Particle();
// Time to live
particle.timeToLive = math.max(life + lifeVar * randMinus1To1(), 0.0);
// Position
Point srcPos = Point.origin;
particle.pos = new Vector2(srcPos.x + posVar.x * randMinus1To1(),
srcPos.y + posVar.y * randMinus1To1());
// Size
particle.size = math.max(startSize + startSizeVar * randMinus1To1(), 0.0);
double endSizeFinal = math.max(endSize + endSizeVar * randMinus1To1(), 0.0);
particle.deltaSize = (endSizeFinal - particle.size) / particle.timeToLive;
// Rotation
particle.rotation = startRotation + startRotationVar * randMinus1To1();
double endRotationFinal = endRotation + endRotationVar * randMinus1To1();
particle.deltaRotation = (endRotationFinal - particle.rotation) / particle.timeToLive;
// Direction
double dirRadians = convertDegrees2Radians(direction + directionVar * randMinus1To1());
Vector2 dirVector = new Vector2(math.cos(dirRadians), math.sin(dirRadians));
double speedFinal = speed + speedVar * randMinus1To1();
particle.dir = dirVector.scale(speedFinal);
// Radial acceleration
particle.radialAccel = radialAcceleration + radialAccelerationVar * randMinus1To1();
// Tangential acceleration
particle.tangentialAccel = tangentialAcceleration + tangentialAccelerationVar * randMinus1To1();
// Color
particle.colorPos = 0.0;
particle.deltaColorPos = 1.0 / particle.timeToLive;
if (alphaVar != 0 || redVar != 0 || greenVar != 0 || blueVar != 0) {
particle.colorSequence = new ColorSequence.copyWithVariance(colorSequence, alphaVar, redVar, greenVar, blueVar);
}
_particles.add(particle);
_numEmittedParticles++;
}
void paint(PaintingCanvas canvas) {
List<RSTransform> transforms = [];
List<Rect> rects = [];
List<Color> colors = [];
for (_Particle particle in _particles) {
// Transform
double scos;
double ssin;
if (rotateToMovement) {
double extraRotation = math.atan2(particle.dir[1], particle.dir[0]);
scos = math.cos(convertDegrees2Radians(particle.rotation) + extraRotation) * particle.size;
ssin = math.sin(convertDegrees2Radians(particle.rotation) + extraRotation) * particle.size;
} else {
scos = math.cos(convertDegrees2Radians(particle.rotation)) * particle.size;
ssin = math.sin(convertDegrees2Radians(particle.rotation)) * particle.size;
}
RSTransform transform = new RSTransform(scos, ssin, particle.pos[0], particle.pos[1]);
transforms.add(transform);
// Rect
Rect rect = texture.frame;
rects.add(rect);
// Color
Color particleColor;
if (particle.colorSequence != null) {
particleColor = particle.colorSequence.colorAtPosition(particle.colorPos);
} else {
particleColor = colorSequence.colorAtPosition(particle.colorPos);
}
colors.add(particleColor);
}
drawAtlas(canvas, texture.image, transforms, rects, colors, TransferMode.modulate,
new Paint()..setTransferMode(transferMode));
}
double randMinus1To1() => _rand.nextDouble() * 2.0 - 1.0;
}
// TODO: Needs bindings to Skia method in SkCanvas (exclude canvas parameter)
void drawAtlas(Canvas canvas, Image image, List<RSTransform> transforms, List<Rect> rects, List<Color> colors,
TransferMode transferMode, Paint paint) {
assert(transforms.length == rects.length && transforms.length == colors.length);
Texture mainTexture = new Texture(image);
for (int i = 0; i < transforms.length; i++) {
RSTransform transform = transforms[i];
Rect rect = rects[i];
Color color = colors[i];
canvas.save();
Matrix4 matrix = new Matrix4(transform.scos, transform.ssin, 0.0, 0.0,
-transform.ssin, transform.scos, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
transform.tx, transform.ty, 0.0, 1.0);
canvas.concat(matrix.storage);
paint.setColorFilter(new ColorFilter.mode(color, transferMode));
paint.color = color;
Texture texture = mainTexture.textureFromRect(rect);
texture.drawTexture(canvas, new Point(-texture.size.width/2.0, -texture.size.height/2.0), paint);
canvas.restore();
}
}
// TODO: Needs bindings to Skia SkRSXform
class RSTransform {
double scos;
double ssin;
double tx;
double ty;
RSTransform(this.scos, this.ssin, this.tx, this.ty);
}

View File

@@ -0,0 +1,114 @@
part of sprites;
/// A Sprite is a [Node] that renders a bitmap image to the screen.
class Sprite extends NodeWithSize {
/// The texture that the sprite will render to screen.
///
/// If the texture is null, the sprite will be rendered as a red square
/// marking the bounds of the sprite.
///
/// mySprite.texture = myTexture;
Texture texture;
/// If true, constrains the proportions of the image by scaling it down, if its proportions doesn't match the [size].
///
/// mySprite.constrainProportions = true;
bool constrainProportions = false;
double _opacity = 1.0;
/// The color to draw on top of the sprite, null if no color overlay is used.
///
/// // Color the sprite red
/// mySprite.colorOverlay = new Color(0x77ff0000);
Color colorOverlay;
/// The transfer mode used when drawing the sprite to screen.
///
/// // Add the colors of the sprite with the colors of the background
/// mySprite.transferMode = TransferMode.plusMode;
TransferMode transferMode;
/// Creates a new sprite from the provided [texture].
///
/// var mySprite = new Sprite(myTexture)
Sprite([this.texture]) {
if (texture != null) {
size = texture.size;
pivot = texture.pivot;
} else {
pivot = new Point(0.5, 0.5);
}
}
/// Creates a new sprite from the provided [image].
///
/// var mySprite = new Sprite.fromImage(myImage);
Sprite.fromImage(Image image) {
assert(image != null);
texture = new Texture(image);
size = texture.size;
pivot = new Point(0.5, 0.5);
}
/// The opacity of the sprite in the range 0.0 to 1.0.
///
/// mySprite.opacity = 0.5;
double get opacity => _opacity;
void set opacity(double opacity) {
assert(opacity != null);
assert(opacity >= 0.0 && opacity <= 1.0);
_opacity = opacity;
}
void paint(PaintingCanvas canvas) {
canvas.save();
// Account for pivot point
applyTransformForPivot(canvas);
if (texture != null) {
double w = texture.size.width;
double h = texture.size.height;
if (w <= 0 || h <= 0) return;
double scaleX = size.width / w;
double scaleY = size.height / h;
if (constrainProportions) {
// Constrain proportions, using the smallest scale and by centering the image
if (scaleX < scaleY) {
canvas.translate(0.0, (size.height - scaleX * h) / 2.0);
scaleY = scaleX;
} else {
canvas.translate((size.width - scaleY * w) / 2.0, 0.0);
scaleX = scaleY;
}
}
canvas.scale(scaleX, scaleY);
// Setup paint object for opacity and transfer mode
Paint paint = new Paint();
paint.color = new Color.fromARGB((255.0*_opacity).toInt(), 255, 255, 255);
if (colorOverlay != null) {
paint.setColorFilter(new ColorFilter.mode(colorOverlay, TransferMode.srcATop));
}
if (transferMode != null) {
paint.setTransferMode(transferMode);
}
// Do actual drawing of the sprite
texture.drawTexture(canvas, Point.origin, paint);
} else {
// Paint a red square for missing texture
canvas.drawRect(new Rect.fromLTRB(0.0, 0.0, size.width, size.height),
new Paint()..color = const Color.fromARGB(255, 255, 0, 0));
}
canvas.restore();
}
}

View File

@@ -0,0 +1,393 @@
part of sprites;
/// Options for setting up a [SpriteBox].
///
/// * [nativePoints], use the same points as the parent [Widget].
/// * [letterbox], use the size of the root node for the coordinate system, constrain the aspect ratio and trim off
/// areas that end up outside the screen.
/// * [stretch], use the size of the root node for the coordinate system, scale it to fit the size of the box.
/// * [scaleToFit], similar to the letterbox option, but instead of trimming areas the sprite system will be scaled
/// down to fit the box.
/// * [fixedWidth], uses the width of the root node to set the size of the coordinate system, this option will change
/// the height of the root node to fit the box.
/// * [fixedHeight], uses the height of the root node to set the size of the coordinate system, this option will change
/// the width of the root node to fit the box.
enum SpriteBoxTransformMode {
nativePoints,
letterbox,
stretch,
scaleToFit,
fixedWidth,
fixedHeight,
}
class SpriteBox extends RenderBox {
// Member variables
// Root node for drawing
NodeWithSize _rootNode;
// Tracking of frame rate and updates
double _lastTimeStamp;
int _numFrames = 0;
double _frameRate = 0.0;
// Transformation mode
SpriteBoxTransformMode _transformMode;
/// The transform mode used by the [SpriteBox].
SpriteBoxTransformMode get transformMode => _transformMode;
// Cached transformation matrix
Matrix4 _transformMatrix;
List<Node> _eventTargets;
// Setup
/// Creates a new SpriteBox with a node as its content, by default uses letterboxing.
///
/// The [rootNode] provides the content of the node tree, typically it's a custom subclass of [NodeWithSize]. The
/// [mode] provides different ways to scale the content to best fit it to the screen. In most cases it's preferred to
/// use a [SpriteWidget] that automatically wraps the SpriteBox.
///
/// var spriteBox = new SpriteBox(myNode, SpriteBoxTransformMode.fixedHeight);
SpriteBox(NodeWithSize rootNode, [SpriteBoxTransformMode mode = SpriteBoxTransformMode.letterbox]) {
assert(rootNode != null);
assert(rootNode._spriteBox == null);
// Setup root node
_rootNode = rootNode;
// Assign SpriteBox reference to all the nodes
_addSpriteBoxReference(_rootNode);
// Setup transform mode
_transformMode = mode;
_scheduleTick();
}
void _addSpriteBoxReference(Node node) {
node._spriteBox = this;
for (Node child in node._children) {
_addSpriteBoxReference(child);
}
}
// Properties
/// The root node of the node tree that is rendered by this box.
///
/// var rootNode = mySpriteBox.rootNode;
NodeWithSize get rootNode => _rootNode;
void performLayout() {
size = constraints.biggest;
_invalidateTransformMatrix();
_callSpriteBoxPerformedLayout(_rootNode);
}
// Event handling
void _addEventTargets(Node node, List<Node> eventTargets) {
List children = node.children;
int i = 0;
// Add childrens that are behind this node
while (i < children.length) {
Node child = children[i];
if (child.zPosition >= 0.0) break;
_addEventTargets(child, eventTargets);
i++;
}
// Add this node
if (node.userInteractionEnabled) {
eventTargets.add(node);
}
// Add children in front of this node
while (i < children.length) {
Node child = children[i];
_addEventTargets(child, eventTargets);
i++;
}
}
void handleEvent(Event event, _SpriteBoxHitTestEntry entry) {
if (event is PointerEvent) {
if (event.type == 'pointerdown') {
// Build list of event targets
if (_eventTargets == null) {
_eventTargets = [];
_addEventTargets(_rootNode, _eventTargets);
}
// Find the once that are hit by the pointer
List<Node> nodeTargets = [];
for (int i = _eventTargets.length - 1; i >= 0; i--) {
Node node = _eventTargets[i];
// Check if the node is ready to handle a pointer
if (node.handleMultiplePointers || node._handlingPointer == null) {
// Do the hit test
Point posInNodeSpace = node.convertPointToNodeSpace(entry.localPosition);
if (node.isPointInside(posInNodeSpace)) {
nodeTargets.add(node);
node._handlingPointer = event.pointer;
}
}
}
entry.nodeTargets = nodeTargets;
}
// Pass the event down to nodes that were hit by the pointerdown
List<Node> targets = entry.nodeTargets;
for (Node node in targets) {
// Check if this event should be dispatched
if (node.handleMultiplePointers || event.pointer == node._handlingPointer) {
// Dispatch event
bool consumedEvent = node.handleEvent(new SpriteBoxEvent(new Point(event.x, event.y), event.type, event.pointer));
if (consumedEvent == null || consumedEvent) break;
}
}
// De-register pointer for nodes that doesn't handle multiple pointers
for (Node node in targets) {
if (event.type == 'pointerup' || event.type == 'pointercancel') {
node._handlingPointer = null;
}
}
}
}
bool hitTest(HitTestResult result, { Point position }) {
result.add(new _SpriteBoxHitTestEntry(this, position));
return true;
}
// Rendering
/// The transformation matrix used to transform the root node to the space of the box.
///
/// It's uncommon to need access to this property.
///
/// var matrix = mySpriteBox.transformMatrix;
Matrix4 get transformMatrix {
// Get cached matrix if available
if (_transformMatrix != null) {
return _transformMatrix;
}
_transformMatrix = new Matrix4.identity();
// Calculate matrix
double scaleX = 1.0;
double scaleY = 1.0;
double offsetX = 0.0;
double offsetY = 0.0;
double systemWidth = rootNode.size.width;
double systemHeight = rootNode.size.height;
switch(_transformMode) {
case SpriteBoxTransformMode.stretch:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
break;
case SpriteBoxTransformMode.letterbox:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
if (scaleX > scaleY) {
scaleY = scaleX;
offsetY = (size.height - scaleY * systemHeight)/2.0;
} else {
scaleX = scaleY;
offsetX = (size.width - scaleX * systemWidth)/2.0;
}
break;
case SpriteBoxTransformMode.scaleToFit:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
if (scaleX < scaleY) {
scaleY = scaleX;
offsetY = (size.height - scaleY * systemHeight)/2.0;
} else {
scaleX = scaleY;
offsetX = (size.width - scaleX * systemWidth)/2.0;
}
break;
case SpriteBoxTransformMode.fixedWidth:
scaleX = size.width/systemWidth;
scaleY = scaleX;
systemHeight = size.height/scaleX;
rootNode.size = new Size(systemWidth, systemHeight);
break;
case SpriteBoxTransformMode.fixedHeight:
scaleY = size.height/systemHeight;
scaleX = scaleY;
systemWidth = size.width/scaleY;
rootNode.size = new Size(systemWidth, systemHeight);
break;
case SpriteBoxTransformMode.nativePoints:
break;
default:
assert(false);
break;
}
_transformMatrix.translate(offsetX, offsetY);
_transformMatrix.scale(scaleX, scaleY);
return _transformMatrix;
}
void _invalidateTransformMatrix() {
_transformMatrix = null;
_rootNode._invalidateToBoxTransformMatrix();
}
void paint(PaintingCanvas canvas, Offset offset) {
canvas.save();
// Move to correct coordinate space before drawing
canvas.translate(offset.dx, offset.dy);
canvas.concat(transformMatrix.storage);
// Draw the sprite tree
_rootNode._visit(canvas);
canvas.restore();
}
// Updates
void _scheduleTick() {
scheduler.requestAnimationFrame(_tick);
}
void _tick(double timeStamp) {
// Calculate the time between frames in seconds
if (_lastTimeStamp == null) _lastTimeStamp = timeStamp;
double delta = (timeStamp - _lastTimeStamp) / 1000;
_lastTimeStamp = timeStamp;
// Count the number of frames we've been running
_numFrames += 1;
_frameRate = 1.0/delta;
// Print frame rate
if (_numFrames % 60 == 0) print("delta: $delta fps: $_frameRate");
_runActions(_rootNode, delta);
_callUpdate(_rootNode, delta);
_scheduleTick();
markNeedsPaint();
}
void _runActions(Node node, double dt) {
if (node._actions != null) {
node._actions.step(dt);
}
for (int i = node.children.length - 1; i >= 0; i--) {
Node child = node.children[i];
_runActions(child, dt);
}
}
void _callUpdate(Node node, double dt) {
node.update(dt);
for (int i = node.children.length - 1; i >= 0; i--) {
Node child = node.children[i];
if (!child.paused) {
_callUpdate(child, dt);
}
}
}
void _callSpriteBoxPerformedLayout(Node node) {
node.spriteBoxPerformedLayout();
for (Node child in node.children) {
_callSpriteBoxPerformedLayout(child);
}
}
// Hit tests
/// Finds all nodes at a position defined in the box's coordinates.
///
/// Use this method with caution. It searches the complete node tree to locate the nodes, which can be slow if the
/// node tree is large.
///
/// List nodes = mySpriteBox.findNodesAtPosition(new Point(50.0, 50.0));
List<Node> findNodesAtPosition(Point position) {
assert(position != null);
List<Node> nodes = [];
// Traverse the render tree and find objects at the position
_addNodesAtPosition(_rootNode, position, nodes);
return nodes;
}
_addNodesAtPosition(Node node, Point position, List<Node> list) {
// Visit children first
for (Node child in node.children) {
_addNodesAtPosition(child, position, list);
}
// Do the hit test
Point posInNodeSpace = node.convertPointToNodeSpace(position);
if (node.isPointInside(posInNodeSpace)) {
list.add(node);
}
}
}
class _SpriteBoxHitTestEntry extends BoxHitTestEntry {
List<Node> nodeTargets;
_SpriteBoxHitTestEntry(RenderBox target, Point localPosition) : super(target, localPosition);
}
/// An event that is passed down the node tree when pointer events occur. The SpriteBoxEvent is typically handled in
/// the handleEvent method of [Node].
class SpriteBoxEvent {
/// The position of the event in box coordinates.
///
/// You can use the convertPointToNodeSpace of [Node] to convert the position to local coordinates.
///
/// bool handleEvent(SpriteBoxEvent event) {
/// Point localPosition = convertPointToNodeSpace(event.boxPosition);
/// if (event.type == 'pointerdown') {
/// // Do something!
/// }
/// }
final Point boxPosition;
/// The type of event, there are currently four valid types, 'pointerdown', 'pointermoved', 'pointerup', and
/// 'pointercancel'.
///
/// if (event.type == 'pointerdown') {
/// // Do something!
/// }
final String type;
/// The id of the pointer. Each pointer on the screen will have a unique pointer id.
///
/// if (event.pointer == firstPointerId) {
/// // Do something
/// }
final int pointer;
/// Creates a new SpriteBoxEvent, typically this is done internally inside the SpriteBox.
///
/// var event = new SpriteBoxEvent(new Point(50.0, 50.0), 'pointerdown', 0);
SpriteBoxEvent(this.boxPosition, this.type, this.pointer);
}

View File

@@ -0,0 +1,38 @@
part of sprites;
/// A widget that uses a [SpriteBox] to render a sprite node tree to the screen.
class SpriteWidget extends OneChildRenderObjectWrapper {
/// The rootNode of the sprite node tree.
///
/// var node = mySpriteWidget.rootNode;
final NodeWithSize rootNode;
/// The transform mode used to fit the sprite node tree to the size of the widget.
final SpriteBoxTransformMode transformMode;
/// Creates a new sprite widget with [rootNode] as its content.
///
/// The widget will setup the coordinate space for the sprite node tree using the size of the [rootNode] in
/// combination with the supplied [transformMode]. By default the letterbox transform mode is used. See
/// [SpriteBoxTransformMode] for more details on the different modes.
///
/// The most common way to setup the sprite node graph is to subclass [NodeWithSize] and pass it to the sprite widget.
/// In the custom subclass it's possible to build the node graph, do animations and handle user events.
///
/// var mySpriteTree = new MyCustomNodeWithSize();
/// var mySpriteWidget = new SpriteWidget(mySpriteTree, SpriteBoxTransformMode.fixedHeight);
SpriteWidget(this.rootNode, [this.transformMode = SpriteBoxTransformMode.letterbox]);
SpriteBox get root => super.root;
SpriteBox createNode() => new SpriteBox(rootNode, transformMode);
void syncRenderObject(SpriteWidget old) {
super.syncRenderObject(old);
// SpriteBox doesn't allow mutation of these properties
assert(rootNode == root.rootNode);
assert(transformMode == root._transformMode);
}
}

View File

@@ -0,0 +1,31 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library sprites;
import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;
import 'dart:sky';
import 'package:sky/animation/curves.dart';
import 'package:sky/base/scheduler.dart' as scheduler;
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/widgets/widget.dart';
import 'package:vector_math/vector_math.dart';
part 'action.dart';
part 'color_secuence.dart';
part 'image_map.dart';
part 'node.dart';
part 'node_with_size.dart';
part 'particle_system.dart';
part 'sprite.dart';
part 'spritesheet.dart';
part 'sprite_box.dart';
part 'sprite_widget.dart';
part 'texture.dart';
part 'util.dart';

View File

@@ -0,0 +1,74 @@
part of sprites;
/// A sprite sheet packs a number of smaller images into a single large image.
///
/// The placement of the smaller images are defined by a json file. The larger image and json file is typically created
/// by a tool such as TexturePacker. The [SpriteSheet] class will take a reference to a larger image and a json string.
/// From the image and the string the [SpriteSheet] creates a number of [Texture] objects. The names of the frames in
/// the sprite sheet definition are used to reference the different textures.
class SpriteSheet {
Image _image;
Map<String, Texture> _textures = new Map();
/// Creates a new sprite sheet from an [_image] and a sprite sheet [jsonDefinition].
///
/// var mySpriteSheet = new SpriteSheet(myImage, jsonString);
SpriteSheet(this._image, String jsonDefinition) {
assert(_image != null);
assert(jsonDefinition != null);
JsonDecoder decoder = new JsonDecoder();
Map file = decoder.convert(jsonDefinition);
assert(file != null);
List frames = file["frames"];
for (Map frameInfo in frames) {
String fileName = frameInfo["filename"];
Rect frame = _readJsonRect(frameInfo["frame"]);
bool rotated = frameInfo["rotated"];
bool trimmed = frameInfo["trimmed"];
Rect spriteSourceSize = _readJsonRect(frameInfo["spriteSourceSize"]);
Size sourceSize = _readJsonSize(frameInfo["sourceSize"]);
Point pivot = _readJsonPoint(frameInfo["pivot"]);
var texture = new Texture._fromSpriteFrame(_image, fileName, sourceSize, rotated, trimmed, frame,
spriteSourceSize, pivot);
_textures[fileName] = texture;
}
}
Rect _readJsonRect(Map data) {
num x = data["x"];
num y = data["y"];
num w = data["w"];
num h = data["h"];
return new Rect.fromLTRB(x.toDouble(), y.toDouble(), (x + w).toDouble(), (y + h).toDouble());
}
Size _readJsonSize(Map data) {
num w = data["w"];
num h = data["h"];
return new Size(w.toDouble(), h.toDouble());
}
Point _readJsonPoint(Map data) {
num x = data["x"];
num y = data["y"];
return new Point(x.toDouble(), y.toDouble());
}
/// The image used by the sprite sheet.
///
/// var spriteSheetImage = mySpriteSheet.image;
Image get image => _image;
/// Returns a texture by its name.
///
/// var myTexture = mySpriteSheet["example.png"];
Texture operator [](String fileName) => _textures[fileName];
}

View File

@@ -0,0 +1,110 @@
part of sprites;
/// A texture represents a rectangular area of an image and is typically used to draw a sprite to the screen.
///
/// Normally you get a reference to a texture from a [SpriteSheet], but you can also create one from an [Image].
class Texture {
/// The image that this texture is a part of.
///
/// var textureImage = myTexture.image;
final Image image;
/// The logical size of the texture, before being trimmed by the texture packer.
///
/// var textureSize = myTexture.size;
final Size size;
/// The name of the image acts as a tag when acquiring a reference to it.
///
/// myTexture.name = "new_texture_name";
String name;
/// The texture was rotated 90 degrees when being packed into a sprite sheet.
///
/// if (myTexture.rotated) drawRotated();
final bool rotated;
/// The texture was trimmed when being packed into a sprite sheet.
///
/// bool trimmed = myTexture.trimmed
final bool trimmed;
/// The frame of the trimmed texture inside the image.
///
/// Rect frame = myTexture.frame;
final Rect frame;
/// The offset and size of the trimmed texture inside the image.
///
/// Position represents the offset from the logical [size], the size of the rect represents the size of the trimmed
/// texture.
///
/// Rect spriteSourceSize = myTexture.spriteSourceSize;
final Rect spriteSourceSize;
/// The default pivot point for this texture. When creating a [Sprite] from the texture, this is the pivot point that
/// will be used.
///
/// myTexture.pivot = new Point(0.5, 0.5);
Point pivot;
/// Creates a new texture from an [Image] object.
///
/// var myTexture = new Texture(myImage);
Texture(Image image) :
size = new Size(image.width.toDouble(), image.height.toDouble()),
image = image,
trimmed = false,
rotated = false,
frame = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
spriteSourceSize = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
pivot = new Point(0.5, 0.5);
Texture._fromSpriteFrame(this.image, this.name, this.size, this.rotated, this.trimmed, this.frame,
this.spriteSourceSize, this.pivot) {
}
Texture textureFromRect(Rect rect, [String name = null]) {
assert(rect != null);
assert(!rotated);
Rect srcFrame = new Rect.fromLTWH(rect.left + frame.left, rect.top + frame.top, rect.size.width, rect.size.height);
Rect dstFrame = new Rect.fromLTWH(0.0, 0.0, rect.size.width, rect.size.height);
return new Texture._fromSpriteFrame(image, name, rect.size, false, false, srcFrame, dstFrame, new Point(0.5, 0.5));
}
void drawTexture(PaintingCanvas canvas, Point position, Paint paint) {
// Account for position
double x = position.x;
double y = position.y;
bool translate = (x != 0 || y != 0);
if (translate) {
canvas.translate(x, y);
}
// Draw the texture
if (rotated) {
// Calculate the rotated frame and spriteSourceSize
Size originalFrameSize = frame.size;
Rect rotatedFrame = frame.topLeft & new Size(originalFrameSize.height, originalFrameSize.width);
Point rotatedSpriteSourcePoint = new Point(
-spriteSourceSize.top - (spriteSourceSize.bottom - spriteSourceSize.top),
spriteSourceSize.left);
Rect rotatedSpriteSourceSize = rotatedSpriteSourcePoint & new Size(originalFrameSize.height, originalFrameSize.width);
// Draw the rotated sprite
canvas.rotate(-math.PI/2.0);
canvas.drawImageRect(image, rotatedFrame, rotatedSpriteSourceSize, paint);
canvas.rotate(math.PI/2.0);
} else {
// Draw the sprite
canvas.drawImageRect(image, frame, spriteSourceSize, paint);
}
// Translate back
if (translate) {
canvas.translate(-x, -y);
}
}
}

View File

@@ -0,0 +1,2 @@
part of sprites;

View File

@@ -0,0 +1,67 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/widget.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/theme.dart';
import 'lib/game_demo.dart';
import 'lib/sprites.dart';
AssetBundle _initBundle() {
if (rootBundle != null)
return rootBundle;
return new NetworkAssetBundle(Uri.base);
}
final AssetBundle _bundle = _initBundle();
ImageMap _loader;
SpriteSheet _spriteSheet;
GameDemoApp _app;
main() async {
_loader = new ImageMap(_bundle);
await _loader.load([
'assets/nebula.png',
'assets/sprites.png',
'assets/starfield.png',
]);
String json = await _bundle.loadString('assets/sprites.json');
_spriteSheet = new SpriteSheet(_loader['assets/sprites.png'], json);
_app = new GameDemoApp();
runApp(_app);
}
class GameDemoApp extends App {
Widget build() {
// TODO(viktork): The task bar purple is the wrong purple, we may need
// a custom theme swatch to match the purples in the sprites.
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Purple
);
return new Theme(
data: theme,
child: new TaskDescription(
label: 'Asteroids',
child: new SpriteWidget(
new GameDemoWorld(_app, _loader, _spriteSheet)
)
)
);
}
}
void resetGame() {
_app.scheduleBuild();
}

View File

@@ -0,0 +1,5 @@
assets:
- assets/nebula.png
- assets/sprites.json
- assets/sprites.png
- assets/starfield.png

View File

@@ -0,0 +1,15 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/widgets/basic.dart';
class HelloWorldApp extends App {
Widget build() {
return new Text('Hello, world!');
}
}
void main() {
runApp(new HelloWorldApp());
}

View File

@@ -0,0 +1,13 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/sky_app.gni")
sky_app("mine_digger") {
main_dart = "lib/main.dart"
if (is_android) {
apk_name = "MineDigger"
}
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.domokit.mine_digger">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name="org.domokit.sky.shell.SkyApplication" android:label="Mine Digger">
<activity android:name="org.domokit.sky.shell.SkyActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
android:hardwareAccelerated="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,376 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'dart:math';
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/scaffold.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/theme.dart';
import 'package:sky/widgets/tool_bar.dart';
// Classic minesweeper-inspired game. The mouse controls are standard except
// for left + right combo which is not implemented. For touch, the duration of
// the pointer determines probing versus flagging.
//
// There are only 3 classes to understand. Game, which is contains all the
// logic and two UI classes: CoveredMineNode and ExposedMineNode, none of them
// holding state.
class Game {
static const int rows = 9;
static const int cols = 9;
static const int totalMineCount = 11;
static const int coveredCell = 0;
static const int explodedCell = 1;
static const int clearedCell = 2;
static const int flaggedCell = 3;
static const int shownCell = 4;
static final List<TextStyle> textStyles = new List<TextStyle>();
final App app;
bool alive;
bool hasWon;
int detectedCount;
int randomSeed;
// |cells| keeps track of the positions of the mines.
List<List<bool>> cells;
// |uiState| keeps track of the visible player progess.
List<List<int>> uiState;
Game(this.app) {
randomSeed = 22;
// Colors for each mine count:
// 0 - none, 1 - blue, 2-green, 3-red, 4-black, 5-dark red .. etc.
textStyles.add(
new TextStyle(color: const Color(0xFF555555), fontWeight: bold));
textStyles.add(
new TextStyle(color: const Color(0xFF0094FF), fontWeight: bold));
textStyles.add(
new TextStyle(color: const Color(0xFF13A023), fontWeight: bold));
textStyles.add(
new TextStyle(color: const Color(0xFFDA1414), fontWeight: bold));
textStyles.add(
new TextStyle(color: const Color(0xFF1E2347), fontWeight: bold));
textStyles.add(
new TextStyle(color: const Color(0xFF7F0037), fontWeight: bold));
textStyles.add(
new TextStyle(color: const Color(0xFFE93BE9), fontWeight: bold));
initialize();
}
void initialize() {
alive = true;
hasWon = false;
detectedCount = 0;
// Build the arrays.
cells = new List<List<bool>>();
uiState = new List<List<int>>();
for (int iy = 0; iy != rows; iy++) {
cells.add(new List<bool>());
uiState.add(new List<int>());
for (int ix = 0; ix != cols; ix++) {
cells[iy].add(false);
uiState[iy].add(coveredCell);
}
}
// Place the mines.
Random random = new Random(++randomSeed);
for (int mc = 0; mc != totalMineCount; mc++) {
int rx = random.nextInt(rows);
int ry = random.nextInt(cols);
if (cells[ry][rx]) {
// Mine already there. Try again.
--mc;
} else {
cells[ry][rx] = true;
}
}
}
Widget buildBoard() {
bool hasCoveredCell = false;
List<Flex> flexRows = new List<Flex>();
for (int iy = 0; iy != 9; iy++) {
List<Component> row = new List<Component>();
for (int ix = 0; ix != 9; ix++) {
int state = uiState[iy][ix];
int count = mineCount(ix, iy);
if (!alive) {
if (state != explodedCell)
state = cells[iy][ix] ? shownCell : state;
}
if (state == coveredCell) {
row.add(new CoveredMineNode(
this,
flagged: false,
posX: ix, posY: iy));
// Mutating |hasCoveredCell| here is hacky, but convenient, same
// goes for mutating |hasWon| below.
hasCoveredCell = true;
} else if (state == flaggedCell) {
row.add(new CoveredMineNode(
this,
flagged: true,
posX: ix, posY: iy));
} else {
row.add(new ExposedMineNode(
state: state,
count: count));
}
}
flexRows.add(
new Flex(
row,
direction: FlexDirection.horizontal,
justifyContent: FlexJustifyContent.center,
key: 'flex_row($iy)'
));
}
if (!hasCoveredCell) {
// all cells uncovered. Are all mines flagged?
if ((detectedCount == totalMineCount) && alive) {
hasWon = true;
}
}
return new Container(
key: 'minefield',
padding: new EdgeDims.all(10.0),
margin: new EdgeDims.all(10.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFF6B6B6B)),
child: new Flex(
flexRows,
direction: FlexDirection.vertical,
key: 'flxv'));
}
Widget buildToolBar() {
String banner = hasWon ?
'Awesome!!' : alive ?
'Mine Digger [$detectedCount-$totalMineCount]': 'Kaboom! [press here]';
return new ToolBar(
// FIXME: Strange to have the toolbar be tapable.
center: new Listener(
onPointerDown: handleBannerPointerDown,
child: new Text(banner, style: Theme.of(this.app).text.title)
)
);
}
Widget buildUI() {
// FIXME: We need to build the board before we build the toolbar because
// we compute the win state during build step.
Widget board = buildBoard();
return new TaskDescription(
label: 'Mine Digger',
child: new Scaffold(
toolbar: buildToolBar(),
body: new Container(
child: new Center(child: board),
decoration: new BoxDecoration(backgroundColor: colors.Grey[50])
)
)
);
}
void handleBannerPointerDown(sky.PointerEvent event) {
initialize();
app.scheduleBuild();
}
// User action. The user uncovers the cell which can cause losing the game.
void probe(int x, int y) {
if (!alive)
return;
if (uiState[y][x] == flaggedCell)
return;
// Allowed to probe.
if (cells[y][x]) {
// Probed on a mine --> dead!!
uiState[y][x] = explodedCell;
alive = false;
} else {
// No mine, uncover nearby if possible.
cull(x, y);
}
app.scheduleBuild();
}
// User action. The user is sure a mine is at this location.
void flag(int x, int y) {
if (uiState[y][x] == flaggedCell) {
uiState[y][x] = coveredCell;
--detectedCount;
} else {
uiState[y][x] = flaggedCell;
++detectedCount;
}
app.scheduleBuild();
}
// Recursively uncovers cells whose totalMineCount is zero.
void cull(int x, int y) {
if ((x < 0) || (x > rows - 1))
return;
if ((y < 0) || (y > cols - 1))
return;
if (uiState[y][x] == clearedCell)
return;
uiState[y][x] = clearedCell;
if (mineCount(x, y) > 0)
return;
cull(x - 1, y);
cull(x + 1, y);
cull(x, y - 1);
cull(x, y + 1 );
cull(x - 1, y - 1);
cull(x + 1, y + 1);
cull(x + 1, y - 1);
cull(x - 1, y + 1);
}
int mineCount(int x, int y) {
int count = 0;
int my = cols - 1;
int mx = rows - 1;
count += x > 0 ? bombs(x - 1, y) : 0;
count += x < mx ? bombs(x + 1, y) : 0;
count += y > 0 ? bombs(x, y - 1) : 0;
count += y < my ? bombs(x, y + 1 ) : 0;
count += (x > 0) && (y > 0) ? bombs(x - 1, y - 1) : 0;
count += (x < mx) && (y < my) ? bombs(x + 1, y + 1) : 0;
count += (x < mx) && (y > 0) ? bombs(x + 1, y - 1) : 0;
count += (x > 0) && (y < my) ? bombs(x - 1, y + 1) : 0;
return count;
}
int bombs(int x, int y) {
return cells[y][x] ? 1 : 0;
}
}
Widget makeCell(Widget widget) {
return new Container(
padding: new EdgeDims.all(1.0),
height: 27.0, width: 27.0,
decoration: new BoxDecoration(backgroundColor: const Color(0xFFC0C0C0)),
margin: new EdgeDims.all(2.0),
child: widget);
}
Widget makeInnerCell(Widget widget) {
return new Container(
padding: new EdgeDims.all(1.0),
margin: new EdgeDims.all(3.0),
height: 17.0, width: 17.0,
child: widget);
}
class CoveredMineNode extends Component {
final Game game;
final bool flagged;
final int posX;
final int posY;
Stopwatch stopwatch;
CoveredMineNode(this.game, {this.flagged, this.posX, this.posY});
void _handlePointerDown(sky.PointerEvent event) {
if (event.buttons == 1) {
game.probe(posX, posY);
} else if (event.buttons == 2) {
game.flag(posX, posY);
} else {
// Touch event.
stopwatch = new Stopwatch()..start();
}
}
void _handlePointerUp(sky.PointerEvent event) {
if (stopwatch == null)
return;
// Pointer down was a touch event.
if (stopwatch.elapsedMilliseconds < 250) {
game.probe(posX, posY);
} else {
// Long press flags.
game.flag(posX, posY);
}
stopwatch = null;
}
Widget build() {
Widget text = flagged ?
makeInnerCell(new StyledText(elements : [Game.textStyles[5], '\u2691'])) :
null;
Container inner = new Container(
margin: new EdgeDims.all(2.0),
height: 17.0, width: 17.0,
decoration: new BoxDecoration(backgroundColor: const Color(0xFFD9D9D9)),
child: text);
return makeCell(new Listener(
child: inner,
onPointerDown: _handlePointerDown,
onPointerUp: _handlePointerUp));
}
}
class ExposedMineNode extends Component {
final int state;
final int count;
ExposedMineNode({this.state, this.count});
Widget build() {
StyledText text;
if (state == Game.clearedCell) {
// Uncovered cell with nearby mine count.
if (count != 0)
text = new StyledText(elements : [Game.textStyles[count], '$count']);
} else {
// Exploded mine or shown mine for 'game over'.
int color = state == Game.explodedCell ? 3 : 0;
text = new StyledText(elements : [Game.textStyles[color], '\u2600']);
}
return makeCell(makeInnerCell(text));
}
}
class MineDiggerApp extends App {
Game game;
MineDiggerApp() {
game = new Game(this);
}
Widget build() {
return game.buildUI();
}
}
void main() {
runApp(new MineDiggerApp());
}

View File

@@ -0,0 +1,65 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
void drawText(sky.Canvas canvas, String lh) {
sky.Paint paint = new sky.Paint();
// offset down
canvas.translate(0.0, 100.0);
// set up the text
sky.Document document = new sky.Document();
sky.Text arabic = document.createText("مرحبا");
sky.Text english = document.createText(" Hello");
sky.Element block = document.createElement('div');
block.style['display'] = 'paragraph';
block.style['font-family'] = 'monospace';
block.style['font-size'] = '50px';
block.style['line-height'] = lh;
block.style['color'] = '#0000A0';
block.appendChild(arabic);
block.appendChild(english);
sky.LayoutRoot layoutRoot = new sky.LayoutRoot();
layoutRoot.rootElement = block;
layoutRoot.maxWidth = sky.view.width - 20.0; // you need to set a width for this to paint
layoutRoot.layout();
// draw a line at the text's baseline
sky.Path path = new sky.Path();
path.moveTo(0.0, 0.0);
path.lineTo(block.maxContentWidth, 0.0);
path.moveTo(0.0, block.alphabeticBaseline);
path.lineTo(block.maxContentWidth, block.alphabeticBaseline);
path.moveTo(0.0, block.height);
path.lineTo(block.maxContentWidth, block.height);
paint.color = const sky.Color(0xFFFF9000);
paint.setStyle(sky.PaintingStyle.stroke);
paint.strokeWidth = 3.0;
canvas.drawPath(path, paint);
// paint the text
layoutRoot.paint(canvas);
}
void main() {
// prepare the rendering
sky.PictureRecorder recorder = new sky.PictureRecorder();
sky.Canvas canvas = new sky.Canvas(recorder, new sky.Rect.fromLTWH(0.0, 0.0, sky.view.width, sky.view.height));
// background
sky.Paint paint = new sky.Paint();
paint.color = const sky.Color(0xFFFFFFFF);
paint.setStyle(sky.PaintingStyle.fill);
canvas.drawRect(new sky.Rect.fromLTRB(0.0, 0.0, sky.view.width, sky.view.height), paint);
canvas.translate(10.0, 0.0);
drawText(canvas, '1.0');
drawText(canvas, 'lh');
// put it on the screen
sky.view.picture = recorder.endRecording();
sky.view.scheduleFrame();
}

View File

@@ -0,0 +1,46 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
Picture draw(int a, int r, int g, int b) {
Size size = new Size(view.width, view.height);
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, Point.origin & size);
double radius = size.shortestSide * 0.45;
Paint paint = new Paint()..color = new Color.fromARGB(a, r, g, b);
canvas.drawCircle(size.center(Point.origin), radius, paint);
return recorder.endRecording();
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
view.picture = draw(255, 0, 0, 255);
view.scheduleFrame();
return true;
}
if (event.type == "pointerup") {
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
return true;
}
if (event.type == "back") {
print("Pressed back button.");
return true;
}
return false;
}
void main() {
print("Hello, world");
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
view.setEventCallback(handleEvent);
}

View File

@@ -0,0 +1,93 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'dart:math' as math;
import 'dart:typed_data';
void beginFrame(double timeStamp) {
sky.Size size = new sky.Size(sky.view.width, sky.view.height);
sky.PictureRecorder recorder = new sky.PictureRecorder();
sky.Canvas canvas = new sky.Canvas(recorder, sky.Point.origin & size);
sky.Paint paint = new sky.Paint();
sky.Point mid = size.center(sky.Point.origin);
double radius = size.shortestSide / 2.0;
canvas.drawPaint(new sky.Paint()..color = const sky.Color(0xFFFFFFFF));
canvas.save();
canvas.translate(-mid.x/2.0, sky.view.height*2.0);
canvas.clipRect(
new sky.Rect.fromLTRB(0.0, -sky.view.height, sky.view.width, radius));
canvas.translate(mid.x, mid.y);
paint.color = const sky.Color.fromARGB(128, 255, 0, 255);
canvas.rotate(math.PI/4.0);
sky.Gradient yellowBlue = new sky.Gradient.linear(
[new sky.Point(-radius, -radius), new sky.Point(0.0, 0.0)],
[const sky.Color(0xFFFFFF00), const sky.Color(0xFF0000FF)]);
canvas.drawRect(new sky.Rect.fromLTRB(-radius, -radius, radius, radius),
new sky.Paint()..setShader(yellowBlue));
// Scale x and y by 0.5.
var scaleMatrix = new Float32List.fromList([
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0,
]);
canvas.concat(scaleMatrix);
paint.color = const sky.Color.fromARGB(128, 0, 255, 0);
canvas.drawCircle(sky.Point.origin, radius, paint);
canvas.restore();
canvas.translate(0.0, 50.0);
var builder = new sky.LayerDrawLooperBuilder()
..addLayerOnTop(
new sky.DrawLooperLayerInfo()
..setOffset(const sky.Offset(150.0, 0.0))
..setColorMode(sky.TransferMode.src)
..setPaintBits(sky.PaintBits.all),
(sky.Paint layerPaint) {
layerPaint.color = const sky.Color.fromARGB(128, 255, 255, 0);
layerPaint.setColorFilter(new sky.ColorFilter.mode(
const sky.Color.fromARGB(128, 0, 0, 255), sky.TransferMode.srcIn));
layerPaint.setMaskFilter(new sky.MaskFilter.blur(
sky.BlurStyle.normal, 3.0, highQuality: true));
})
..addLayerOnTop(
new sky.DrawLooperLayerInfo()
..setOffset(const sky.Offset(75.0, 75.0))
..setColorMode(sky.TransferMode.src)
..setPaintBits(sky.PaintBits.shader),
(sky.Paint layerPaint) {
sky.Gradient redYellow = new sky.Gradient.radial(
new sky.Point(0.0, 0.0), radius/3.0,
[const sky.Color(0xFFFFFF00), const sky.Color(0xFFFF0000)],
null, sky.TileMode.mirror);
layerPaint.setShader(redYellow);
// Since we're don't set sky.PaintBits.maskFilter, this has no effect.
layerPaint.setMaskFilter(new sky.MaskFilter.blur(
sky.BlurStyle.normal, 50.0, highQuality: true));
})
..addLayerOnTop(
new sky.DrawLooperLayerInfo()..setOffset(const sky.Offset(225.0, 75.0)),
(sky.Paint layerPaint) {
// Since this layer uses a DST color mode, this has no effect.
layerPaint.color = const sky.Color.fromARGB(128, 255, 0, 0);
});
paint.setDrawLooper(builder.build());
canvas.drawCircle(sky.Point.origin, radius, paint);
sky.view.picture = recorder.endRecording();
}
void main() {
sky.view.setFrameCallback(beginFrame);
sky.view.scheduleFrame();
}

View File

@@ -0,0 +1,54 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
PaintingNode paintingNode = null;
Picture draw(int a, int r, int g, int b) {
Rect bounds = new Rect.fromLTRB(0.0, 0.0, view.width, view.height);
Size size = new Size(view.width, view.height);
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, bounds);
double radius = size.shortestSide * 0.45;
Paint paint = new Paint()..color = new Color.fromARGB(a, r, g, b);
canvas.drawCircle(size.center(Point.origin), radius, paint);
if (paintingNode == null) {
paintingNode = new PaintingNode();
Paint innerPaint = new Paint()..color = new Color.fromARGB(a, 255 - r, 255 - g, 255 - b);
PictureRecorder innerRecorder = new PictureRecorder();
Canvas innerCanvas = new Canvas(innerRecorder, bounds);
innerCanvas.drawCircle(size.center(Point.origin), radius * 0.5, innerPaint);
paintingNode.setBackingDrawable(innerRecorder.endRecordingAsDrawable());
}
canvas.drawPaintingNode(paintingNode, Point.origin);
return recorder.endRecording();
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
view.picture = draw(255, 0, 0, 255);
view.scheduleFrame();
return true;
}
if (event.type == "pointerup") {
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
return true;
}
return false;
}
void main() {
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
view.setEventCallback(handleEvent);
}

View File

@@ -0,0 +1,40 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
void beginFrame(double timeStamp) {
double size = 100.0;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, new Rect.fromLTWH(0.0, 0.0, view.width, view.height));
canvas.translate(size + 10.0, size + 10.0);
Paint paint = new Paint();
paint.color = const Color.fromARGB(255, 0, 255, 0);
var builder = new LayerDrawLooperBuilder()
// Shadow layer.
..addLayerOnTop(
new DrawLooperLayerInfo()
..setPaintBits(PaintBits.all)
..setOffset(const Offset(5.0, 5.0))
..setColorMode(TransferMode.src),
(Paint layerPaint) {
layerPaint.color = const Color.fromARGB(128, 55, 55, 55);
layerPaint.setMaskFilter(
new MaskFilter.blur(BlurStyle.normal, 5.0, highQuality: true));
})
// Main layer.
..addLayerOnTop(new DrawLooperLayerInfo(), (Paint) {});
paint.setDrawLooper(builder.build());
canvas.drawPaint(
new Paint()..color = const Color.fromARGB(255, 255, 255, 255));
canvas.drawRect(new Rect.fromLTRB(-size, -size, size, size), paint);
view.picture = recorder.endRecording();
}
void main() {
view.setFrameCallback(beginFrame);
view.scheduleFrame();
}

View File

@@ -0,0 +1,48 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import "dart:math" as math;
import 'dart:sky';
double timeBase = null;
LayoutRoot layoutRoot = new LayoutRoot();
void beginFrame(double timeStamp) {
if (timeBase == null)
timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, new Rect.fromLTWH(0.0, 0.0, view.width, view.height));
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.drawRect(new Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
new Paint()..color = const Color.fromARGB(255, 0, 255, 0));
double sin = math.sin(delta / 200);
layoutRoot.maxWidth = 150.0 + (50 * sin);
layoutRoot.layout();
canvas.translate(layoutRoot.maxWidth / -2.0, (layoutRoot.maxWidth / 2.0) - 125);
layoutRoot.paint(canvas);
view.picture = recorder.endRecording();
view.scheduleFrame();
}
void main() {
var document = new Document();
var arabic = document.createText("هذا هو قليلا طويلة من النص الذي يجب التفاف .");
var more = document.createText(" و أكثر قليلا لجعله أطول. ");
var block = document.createElement('p');
block.style['display'] = 'paragraph';
block.style['direction'] = 'rtl';
block.style['unicode-bidi'] = 'plaintext';
block.appendChild(arabic);
block.appendChild(more);
layoutRoot.rootElement = block;
view.setFrameCallback(beginFrame);
view.scheduleFrame();
}

View File

@@ -0,0 +1,73 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:sky';
import 'package:sky/mojo/net/image_cache.dart' as image_cache;
double timeBase = null;
Image image = null;
String url1 = "https://www.dartlang.org/logos/dart-logo.png";
String url2 = "http://i2.kym-cdn.com/photos/images/facebook/000/581/296/c09.jpg";
void beginFrame(double timeStamp) {
if (timeBase == null)
timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, Point.origin & new Size(view.width, view.height));
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.scale(0.2, 0.2);
Paint paint = new Paint()..color = const Color.fromARGB(255, 0, 255, 0);
// Draw image
if (image != null)
canvas.drawImage(image, new Point(-image.width / 2.0, -image.height / 2.0), paint);
// Draw cut out of image
canvas.rotate(math.PI * delta / 1800);
if (image != null) {
var w = image.width.toDouble();
var h = image.width.toDouble();
canvas.drawImageRect(image,
new Rect.fromLTRB(w * 0.25, h * 0.25, w * 0.75, h * 0.75),
new Rect.fromLTRB(-w / 4.0, -h / 4.0, w / 4.0, h / 4.0),
paint);
}
view.picture = recorder.endRecording();
view.scheduleFrame();
}
void handleImageLoad(result) {
if (result != image) {
print("${result.width}x${result.width} image loaded!");
image = result;
view.scheduleFrame();
} else {
print("Existing image was loaded again");
}
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
return true;
}
if (event.type == "pointerup") {
image_cache.load(url2).then(handleImageLoad);
return true;
}
return false;
}
void main() {
image_cache.load(url1).then(handleImageLoad);
view.setEventCallback(handleEvent);
view.setFrameCallback(beginFrame);
}

View File

@@ -0,0 +1,29 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'dart:math' as math;
double timeBase = null;
void beginFrame(double timeStamp) {
tracing.begin('beginFrame');
if (timeBase == null)
timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, new Rect.fromLTWH(0.0, 0.0, view.width, view.height));
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.drawRect(new Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
new Paint()..color = const Color.fromARGB(255, 0, 255, 0));
view.picture = recorder.endRecording();
view.scheduleFrame();
tracing.end('beginFrame');
}
void main() {
view.setFrameCallback(beginFrame);
view.scheduleFrame();
}

View File

@@ -0,0 +1,17 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/skyx.gni")
skyx("interactive_flex") {
main_dart = "interactive_flex.dart"
}
group("rendering") {
testonly = true
deps = [
":interactive_flex",
]
}

View File

@@ -0,0 +1,81 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
RenderBox getBox(double lh) {
RenderParagraph paragraph = new RenderParagraph(
new InlineStyle(
new TextStyle(
color: const Color(0xFF0000A0)
),
[
new InlineText('test'),
new InlineStyle(
new TextStyle(
fontFamily: 'serif',
fontSize: 50.0,
height: lh
),
[new InlineText('مرحبا Hello')]
)
]
)
);
return new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 200.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: const Color(0xFFFFFFFF)
),
child: new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderCustomPaint(
child: paragraph,
callback: (canvas, size) {
double baseline = paragraph.getDistanceToBaseline(TextBaseline.alphabetic);
double w = paragraph.getMaxIntrinsicWidth(new BoxConstraints.loose(size));
double h = paragraph.getMaxIntrinsicHeight(new BoxConstraints.loose(size));
Path path = new Path();
path.moveTo(0.0, 0.0);
path.lineTo(w, 0.0);
path.moveTo(0.0, baseline);
path.lineTo(w, baseline);
path.moveTo(0.0, h);
path.lineTo(w, h);
Paint paint = new Paint();
paint.color = const Color(0xFFFF9000);
paint.setStyle(sky.PaintingStyle.stroke);
paint.strokeWidth = 3.0;
canvas.drawPath(path, paint);
}
)
)
)
)
);
}
void main() {
RenderBox root = new RenderFlex(children: [
new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 50.0)
),
getBox(1.0),
getBox(null),
],
direction: FlexDirection.vertical,
alignItems: FlexAlignItems.stretch
);
new SkyBinding(root: root);
}

View File

@@ -0,0 +1,76 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/rendering/block.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/sky_binding.dart';
void main() {
var root = new RenderBlock(children: [
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: new sky.Color(0xFFFFFF00)
)
)
)
),
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
border: new Border(
top: new BorderSide(color: new sky.Color(0xFFF00000), width: 5.0),
right: new BorderSide(color: new sky.Color(0xFFFF9000), width: 10.0),
bottom: new BorderSide(color: new sky.Color(0xFFFFF000), width: 15.0),
left: new BorderSide(color: new sky.Color(0xFF00FF00), width: 20.0)
),
backgroundColor: new sky.Color(0xFFDDDDDD)
)
)
)
),
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: new sky.Color(0xFFFFFF00)
)
)
)
),
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: new sky.Color(0xFFFFFF00)
)
)
)
),
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 100.0),
child: new RenderDecoratedBox(
decoration: new BoxDecoration(
backgroundColor: new sky.Color(0xFFFFFF00)
)
)
)
),
]);
new SkyBinding(root: root);
}

View File

@@ -0,0 +1,93 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/sky_binding.dart';
class RenderSolidColor extends RenderDecoratedBox {
final sky.Size desiredSize;
final sky.Color backgroundColor;
RenderSolidColor(sky.Color backgroundColor, { this.desiredSize: sky.Size.infinite })
: backgroundColor = backgroundColor,
super(decoration: new BoxDecoration(backgroundColor: backgroundColor)) {
}
double getMinIntrinsicWidth(BoxConstraints constraints) {
return constraints.constrainWidth(desiredSize.width);
}
double getMaxIntrinsicWidth(BoxConstraints constraints) {
return constraints.constrainWidth(desiredSize.width);
}
double getMinIntrinsicHeight(BoxConstraints constraints) {
return constraints.constrainHeight(desiredSize.height);
}
double getMaxIntrinsicHeight(BoxConstraints constraints) {
return constraints.constrainHeight(desiredSize.height);
}
void performLayout() {
size = constraints.constrain(desiredSize);
}
void handleEvent(sky.Event event, BoxHitTestEntry entry) {
if (event.type == 'pointerdown')
decoration = new BoxDecoration(backgroundColor: const sky.Color(0xFFFF0000));
else if (event.type == 'pointerup')
decoration = new BoxDecoration(backgroundColor: backgroundColor);
}
}
RenderBox buildFlexExample() {
RenderFlex flexRoot = new RenderFlex(direction: FlexDirection.vertical);
RenderDecoratedBox root = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const sky.Color(0xFF000000)),
child: flexRoot
);
void addFlexChildSolidColor(RenderFlex parent, sky.Color backgroundColor, { int flex: 0 }) {
RenderSolidColor child = new RenderSolidColor(backgroundColor);
parent.add(child);
child.parentData.flex = flex;
}
// Yellow bar at top
addFlexChildSolidColor(flexRoot, const sky.Color(0xFFFFFF00), flex: 1);
// Turquoise box
flexRoot.add(new RenderSolidColor(const sky.Color(0x7700FFFF), desiredSize: new sky.Size(100.0, 100.0)));
var renderDecoratedBlock = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const sky.Color(0xFFFFFFFF))
);
flexRoot.add(new RenderPadding(padding: const EdgeDims.all(10.0), child: renderDecoratedBlock));
var row = new RenderFlex(direction: FlexDirection.horizontal);
// Purple and blue cells
addFlexChildSolidColor(row, const sky.Color(0x77FF00FF), flex: 1);
addFlexChildSolidColor(row, const sky.Color(0xFF0000FF), flex: 2);
var decoratedRow = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const sky.Color(0xFF333333)),
child: row
);
flexRoot.add(decoratedRow);
decoratedRow.parentData.flex = 3;
return root;
}
void main() {
new SkyBinding(root: buildFlexExample());
}

View File

@@ -0,0 +1,109 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'dart:math' as math;
import 'package:sky/mojo/activity.dart' as activity;
import 'package:sky/mojo/net/image_cache.dart' as image_cache;
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'solid_color_box.dart';
class Touch {
final double x;
final double y;
const Touch(this.x, this.y);
}
class RenderImageGrow extends RenderImage {
final Size _startingSize;
RenderImageGrow(Image image, Size size) : _startingSize = size, super(image, size);
double _growth = 0.0;
double get growth => _growth;
void set growth(double value) {
_growth = value;
double newWidth = _startingSize.width == null ? null : _startingSize.width + growth;
double newHeight = _startingSize.height == null ? null : _startingSize.height + growth;
requestedSize = new Size(newWidth, newHeight);
}
}
RenderImageGrow image;
Map<int, Touch> touches = new Map();
void handleEvent(event) {
if (event is PointerEvent) {
if (event.type == 'pointermove')
image.growth = math.max(0.0, image.growth + event.x - touches[event.pointer].x);
touches[event.pointer] = new Touch(event.x, event.y);
}
if (event.type == "back") {
activity.finishCurrentActivity();
}
}
void main() {
void addFlexChildSolidColor(RenderFlex parent, Color backgroundColor, { int flex: 0 }) {
RenderSolidColorBox child = new RenderSolidColorBox(backgroundColor);
parent.add(child);
child.parentData.flex = flex;
}
var row = new RenderFlex(direction: FlexDirection.horizontal);
// Left cell
addFlexChildSolidColor(row, const Color(0xFF00D2B8), flex: 1);
// Resizeable image
image = new RenderImageGrow(null, new Size(100.0, null));
image_cache.load("https://www.dartlang.org/logos/dart-logo.png").then((Image dartLogo) {
image.image = dartLogo;
});
var padding = new RenderPadding(padding: const EdgeDims.all(10.0), child: image);
row.add(padding);
RenderFlex column = new RenderFlex(direction: FlexDirection.vertical);
// Top cell
final Color topColor = const Color(0xFF55DDCA);
addFlexChildSolidColor(column, topColor, flex: 1);
// The internet is a beautiful place. https://baconipsum.com/
String meatyString = """Bacon ipsum dolor amet ham fatback tri-tip, prosciutto
porchetta bacon kevin meatball meatloaf pig beef ribs chicken. Brisket ribeye
andouille leberkas capicola meatloaf. Chicken pig ball tip pork picanha bresaola
alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl.
Pancetta meatball tongue tenderloin rump tail jowl boudin.""";
var text = new InlineStyle(
new TextStyle(color: const Color(0xFF009900)),
[new InlineText(meatyString)]);
padding = new RenderPadding(
padding: const EdgeDims.all(10.0),
child: new RenderParagraph(text));
column.add(padding);
// Bottom cell
addFlexChildSolidColor(column, const Color(0xFF0081C6), flex: 2);
row.add(column);
column.parentData.flex = 8;
RenderDecoratedBox root = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: row
);
activity.updateTaskDescription('Interactive Flex', topColor);
new SkyBinding(root: root);
view.setEventCallback(handleEvent);
}

View File

@@ -0,0 +1,47 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'solid_color_box.dart';
const TextStyle style = const TextStyle(color: const Color(0xFF000000));
// Attempts to draw
// http://www.w3.org/TR/2015/WD-css-flexbox-1-20150514/images/flex-pack.svg
void main() {
var table = new RenderFlex(direction: FlexDirection.vertical);
void addRow(FlexJustifyContent justify) {
RenderParagraph paragraph = new RenderParagraph(new InlineStyle(style, [new InlineText("${justify}")]));
table.add(new RenderPadding(child: paragraph, padding: new EdgeDims.only(top: 20.0)));
var row = new RenderFlex(direction: FlexDirection.horizontal);
row.add(new RenderSolidColorBox(const Color(0xFFFFCCCC), desiredSize: new Size(80.0, 60.0)));
row.add(new RenderSolidColorBox(const Color(0xFFCCFFCC), desiredSize: new Size(64.0, 60.0)));
row.add(new RenderSolidColorBox(const Color(0xFFCCCCFF), desiredSize: new Size(160.0, 60.0)));
row.justifyContent = justify;
table.add(row);
row.parentData.flex = 1;
}
addRow(FlexJustifyContent.start);
addRow(FlexJustifyContent.end);
addRow(FlexJustifyContent.center);
addRow(FlexJustifyContent.spaceBetween);
addRow(FlexJustifyContent.spaceAround);
RenderDecoratedBox root = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: new RenderPadding(child: table, padding: new EdgeDims.symmetric(vertical: 50.0))
);
new SkyBinding(root: root);
}

View File

@@ -0,0 +1,46 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'solid_color_box.dart';
void main() {
RenderFlex flexRoot = new RenderFlex(direction: FlexDirection.vertical);
RenderObject root = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFF606060)),
child: flexRoot
);
RenderObject child = new RenderSolidColorBox(const Color(0xFFFFFF00));
flexRoot.add(child);
child.parentData.flex = 2;
// The internet is a beautiful place. https://baconipsum.com/
String meatyString = """Bacon ipsum dolor amet ham fatback tri-tip, prosciutto
porchetta bacon kevin meatball meatloaf pig beef ribs chicken. Brisket ribeye
andouille leberkas capicola meatloaf. Chicken pig ball tip pork picanha bresaola
alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl.
Pancetta meatball tongue tenderloin rump tail jowl boudin.""";
var text = new InlineStyle(
new TextStyle(color: const Color(0xFF009900)),
[new InlineText(meatyString)]);
child = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: new RenderParagraph(text)
);
flexRoot.add(child);
child.parentData.flex = 1;
new SkyBinding(root: root);
}

View File

@@ -0,0 +1,542 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:sky' as sky;
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/sky_binding.dart';
const double kTwoPi = 2 * math.PI;
class SectorConstraints extends Constraints {
const SectorConstraints({
this.minDeltaRadius: 0.0,
this.maxDeltaRadius: double.INFINITY,
this.minDeltaTheta: 0.0,
this.maxDeltaTheta: kTwoPi
});
const SectorConstraints.tight({ double deltaRadius: 0.0, double deltaTheta: 0.0 })
: minDeltaRadius = deltaRadius,
maxDeltaRadius = deltaRadius,
minDeltaTheta = deltaTheta,
maxDeltaTheta = deltaTheta;
final double minDeltaRadius;
final double maxDeltaRadius;
final double minDeltaTheta;
final double maxDeltaTheta;
double constrainDeltaRadius(double deltaRadius) {
return clamp(min: minDeltaRadius, max: maxDeltaRadius, value: deltaRadius);
}
double constrainDeltaTheta(double deltaTheta) {
return clamp(min: minDeltaTheta, max: maxDeltaTheta, value: deltaTheta);
}
bool get isTight => minDeltaTheta >= maxDeltaTheta && minDeltaTheta >= maxDeltaTheta;
}
class SectorDimensions {
const SectorDimensions({ this.deltaRadius: 0.0, this.deltaTheta: 0.0 });
factory SectorDimensions.withConstraints(
SectorConstraints constraints,
{ double deltaRadius: 0.0, double deltaTheta: 0.0 }
) {
return new SectorDimensions(
deltaRadius: constraints.constrainDeltaRadius(deltaRadius),
deltaTheta: constraints.constrainDeltaTheta(deltaTheta)
);
}
final double deltaRadius;
final double deltaTheta;
}
class SectorParentData extends ParentData {
double radius = 0.0;
double theta = 0.0;
}
abstract class RenderSector extends RenderObject {
void setupParentData(RenderObject child) {
if (child.parentData is! SectorParentData)
child.parentData = new SectorParentData();
}
SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) {
return new SectorDimensions.withConstraints(constraints);
}
SectorConstraints get constraints => super.constraints;
bool debugDoesMeetConstraints() {
assert(constraints != null);
assert(deltaRadius != null);
assert(deltaRadius < double.INFINITY);
assert(deltaTheta != null);
assert(deltaTheta < double.INFINITY);
return constraints.minDeltaRadius <= deltaRadius &&
deltaRadius <= math.max(constraints.minDeltaRadius, constraints.maxDeltaRadius) &&
constraints.minDeltaTheta <= deltaTheta &&
deltaTheta <= math.max(constraints.minDeltaTheta, constraints.maxDeltaTheta);
}
void performResize() {
// default behaviour for subclasses that have sizedByParent = true
deltaRadius = constraints.constrainDeltaRadius(0.0);
deltaTheta = constraints.constrainDeltaTheta(0.0);
}
void performLayout() {
// descendants have to either override performLayout() to set both
// the dimensions and lay out children, or, set sizedByParent to
// true so that performResize()'s logic above does its thing.
assert(sizedByParent);
}
Rect get paintBounds => new Rect.fromLTWH(0.0, 0.0, 2.0 * deltaRadius, 2.0 * deltaRadius);
bool hitTest(HitTestResult result, { double radius, double theta }) {
assert(parentData is SectorParentData);
if (radius < parentData.radius || radius >= parentData.radius + deltaRadius ||
theta < parentData.theta || theta >= parentData.theta + deltaTheta)
return false;
hitTestChildren(result, radius: radius, theta: theta);
result.add(new HitTestEntry(this));
return true;
}
void hitTestChildren(HitTestResult result, { double radius, double theta }) { }
double deltaRadius;
double deltaTheta;
}
abstract class RenderDecoratedSector extends RenderSector {
RenderDecoratedSector(BoxDecoration decoration) : _decoration = decoration;
BoxDecoration _decoration;
BoxDecoration get decoration => _decoration;
void set decoration (BoxDecoration value) {
if (value == _decoration)
return;
_decoration = value;
markNeedsPaint();
}
// offset must point to the center of the circle
void paint(PaintingCanvas canvas, Offset offset) {
assert(deltaRadius != null);
assert(deltaTheta != null);
assert(parentData is SectorParentData);
if (_decoration == null)
return;
if (_decoration.backgroundColor != null) {
Paint paint = new Paint()..color = _decoration.backgroundColor;
Path path = new Path();
double outerRadius = (parentData.radius + deltaRadius);
Rect outerBounds = new Rect.fromLTRB(offset.dx-outerRadius, offset.dy-outerRadius, offset.dx+outerRadius, offset.dy+outerRadius);
path.arcTo(outerBounds, parentData.theta, deltaTheta, true);
double innerRadius = parentData.radius;
Rect innerBounds = new Rect.fromLTRB(offset.dx-innerRadius, offset.dy-innerRadius, offset.dx+innerRadius, offset.dy+innerRadius);
path.arcTo(innerBounds, parentData.theta + deltaTheta, -deltaTheta, false);
path.close();
canvas.drawPath(path, paint);
}
}
}
class SectorChildListParentData extends SectorParentData with ContainerParentDataMixin<RenderSector> { }
class RenderSectorWithChildren extends RenderDecoratedSector with ContainerRenderObjectMixin<RenderSector, SectorChildListParentData> {
RenderSectorWithChildren(BoxDecoration decoration) : super(decoration);
void hitTestChildren(HitTestResult result, { double radius, double theta }) {
RenderSector child = lastChild;
while (child != null) {
assert(child.parentData is SectorChildListParentData);
if (child.hitTest(result, radius: radius, theta: theta))
return;
child = child.parentData.previousSibling;
}
}
}
class RenderSectorRing extends RenderSectorWithChildren {
// lays out RenderSector children in a ring
RenderSectorRing({
BoxDecoration decoration,
double deltaRadius: double.INFINITY,
double padding: 0.0
}) : super(decoration), _padding = padding, _desiredDeltaRadius = deltaRadius;
double _desiredDeltaRadius;
double get desiredDeltaRadius => _desiredDeltaRadius;
void set desiredDeltaRadius(double value) {
assert(value != null);
if (_desiredDeltaRadius != value) {
_desiredDeltaRadius = value;
markNeedsLayout();
}
}
double _padding;
double get padding => _padding;
void set padding(double value) {
// TODO(ianh): avoid code duplication
assert(value != null);
if (_padding != value) {
_padding = value;
markNeedsLayout();
}
}
void setupParentData(RenderObject child) {
// TODO(ianh): avoid code duplication
if (child.parentData is! SectorChildListParentData)
child.parentData = new SectorChildListParentData();
}
SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) {
double outerDeltaRadius = constraints.constrainDeltaRadius(desiredDeltaRadius);
double innerDeltaRadius = outerDeltaRadius - padding * 2.0;
double childRadius = radius + padding;
double paddingTheta = math.atan(padding / (radius + outerDeltaRadius));
double innerTheta = paddingTheta; // increments with each child
double remainingDeltaTheta = constraints.maxDeltaTheta - (innerTheta + paddingTheta);
RenderSector child = firstChild;
while (child != null) {
SectorConstraints innerConstraints = new SectorConstraints(
maxDeltaRadius: innerDeltaRadius,
maxDeltaTheta: remainingDeltaTheta
);
SectorDimensions childDimensions = child.getIntrinsicDimensions(innerConstraints, childRadius);
innerTheta += childDimensions.deltaTheta;
remainingDeltaTheta -= childDimensions.deltaTheta;
assert(child.parentData is SectorChildListParentData);
child = child.parentData.nextSibling;
if (child != null) {
innerTheta += paddingTheta;
remainingDeltaTheta -= paddingTheta;
}
}
return new SectorDimensions.withConstraints(constraints,
deltaRadius: outerDeltaRadius,
deltaTheta: innerTheta);
}
void performLayout() {
assert(this.parentData is SectorParentData);
deltaRadius = constraints.constrainDeltaRadius(desiredDeltaRadius);
assert(deltaRadius < double.INFINITY);
double innerDeltaRadius = deltaRadius - padding * 2.0;
double childRadius = this.parentData.radius + padding;
double paddingTheta = math.atan(padding / (this.parentData.radius + deltaRadius));
double innerTheta = paddingTheta; // increments with each child
double remainingDeltaTheta = constraints.maxDeltaTheta - (innerTheta + paddingTheta);
RenderSector child = firstChild;
while (child != null) {
SectorConstraints innerConstraints = new SectorConstraints(
maxDeltaRadius: innerDeltaRadius,
maxDeltaTheta: remainingDeltaTheta
);
assert(child.parentData is SectorParentData);
child.parentData.theta = innerTheta;
child.parentData.radius = childRadius;
child.layout(innerConstraints, parentUsesSize: true);
innerTheta += child.deltaTheta;
remainingDeltaTheta -= child.deltaTheta;
assert(child.parentData is SectorChildListParentData);
child = child.parentData.nextSibling;
if (child != null) {
innerTheta += paddingTheta;
remainingDeltaTheta -= paddingTheta;
}
}
deltaTheta = innerTheta;
}
// offset must point to the center of our circle
// each sector then knows how to paint itself at its location
void paint(PaintingCanvas canvas, Offset offset) {
// TODO(ianh): avoid code duplication
super.paint(canvas, offset);
RenderSector child = firstChild;
while (child != null) {
assert(child.parentData is SectorChildListParentData);
canvas.paintChild(child, offset.toPoint());
child = child.parentData.nextSibling;
}
}
}
class RenderSectorSlice extends RenderSectorWithChildren {
// lays out RenderSector children in a stack
RenderSectorSlice({
BoxDecoration decoration,
double deltaTheta: kTwoPi,
double padding: 0.0
}) : super(decoration), _padding = padding, _desiredDeltaTheta = deltaTheta;
double _desiredDeltaTheta;
double get desiredDeltaTheta => _desiredDeltaTheta;
void set desiredDeltaTheta(double value) {
assert(value != null);
if (_desiredDeltaTheta != value) {
_desiredDeltaTheta = value;
markNeedsLayout();
}
}
double _padding;
double get padding => _padding;
void set padding(double value) {
// TODO(ianh): avoid code duplication
assert(value != null);
if (_padding != value) {
_padding = value;
markNeedsLayout();
}
}
void setupParentData(RenderObject child) {
// TODO(ianh): avoid code duplication
if (child.parentData is! SectorChildListParentData)
child.parentData = new SectorChildListParentData();
}
SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) {
assert(this.parentData is SectorParentData);
double paddingTheta = math.atan(padding / this.parentData.radius);
double outerDeltaTheta = constraints.constrainDeltaTheta(desiredDeltaTheta);
double innerDeltaTheta = outerDeltaTheta - paddingTheta * 2.0;
double childRadius = this.parentData.radius + padding;
double remainingDeltaRadius = constraints.maxDeltaRadius - (padding * 2.0);
RenderSector child = firstChild;
while (child != null) {
SectorConstraints innerConstraints = new SectorConstraints(
maxDeltaRadius: remainingDeltaRadius,
maxDeltaTheta: innerDeltaTheta
);
SectorDimensions childDimensions = child.getIntrinsicDimensions(innerConstraints, childRadius);
childRadius += childDimensions.deltaRadius;
remainingDeltaRadius -= childDimensions.deltaRadius;
assert(child.parentData is SectorChildListParentData);
child = child.parentData.nextSibling;
childRadius += padding;
remainingDeltaRadius -= padding;
}
return new SectorDimensions.withConstraints(constraints,
deltaRadius: childRadius - this.parentData.radius,
deltaTheta: outerDeltaTheta);
}
void performLayout() {
assert(this.parentData is SectorParentData);
deltaTheta = constraints.constrainDeltaTheta(desiredDeltaTheta);
assert(deltaTheta <= kTwoPi);
double paddingTheta = math.atan(padding / this.parentData.radius);
double innerTheta = this.parentData.theta + paddingTheta;
double innerDeltaTheta = deltaTheta - paddingTheta * 2.0;
double childRadius = this.parentData.radius + padding;
double remainingDeltaRadius = constraints.maxDeltaRadius - (padding * 2.0);
RenderSector child = firstChild;
while (child != null) {
SectorConstraints innerConstraints = new SectorConstraints(
maxDeltaRadius: remainingDeltaRadius,
maxDeltaTheta: innerDeltaTheta
);
child.parentData.theta = innerTheta;
child.parentData.radius = childRadius;
child.layout(innerConstraints, parentUsesSize: true);
childRadius += child.deltaRadius;
remainingDeltaRadius -= child.deltaRadius;
assert(child.parentData is SectorChildListParentData);
child = child.parentData.nextSibling;
childRadius += padding;
remainingDeltaRadius -= padding;
}
deltaRadius = childRadius - this.parentData.radius;
}
// offset must point to the center of our circle
// each sector then knows how to paint itself at its location
void paint(PaintingCanvas canvas, Offset offset) {
// TODO(ianh): avoid code duplication
super.paint(canvas, offset);
RenderSector child = firstChild;
while (child != null) {
assert(child.parentData is SectorChildListParentData);
canvas.paintChild(child, offset.toPoint());
child = child.parentData.nextSibling;
}
}
}
class RenderBoxToRenderSectorAdapter extends RenderBox {
RenderBoxToRenderSectorAdapter({ double innerRadius: 0.0, RenderSector child }) :
_innerRadius = innerRadius {
_child = child;
adoptChild(_child);
}
double _innerRadius;
double get innerRadius => _innerRadius;
void set innerRadius(double value) {
_innerRadius = value;
markNeedsLayout();
}
RenderSector _child;
RenderSector get child => _child;
void set child(RenderSector value) {
if (_child != null)
dropChild(_child);
_child = value;
adoptChild(_child);
markNeedsLayout();
}
void setupParentData(RenderObject child) {
if (child.parentData is! SectorParentData)
child.parentData = new SectorParentData();
}
double getMinIntrinsicWidth(BoxConstraints constraints) {
if (child == null)
return super.getMinIntrinsicWidth(constraints);
return getIntrinsicDimensions(constraints).width;
}
double getMaxIntrinsicWidth(BoxConstraints constraints) {
if (child == null)
return super.getMaxIntrinsicWidth(constraints);
return getIntrinsicDimensions(constraints).width;
}
double getMinIntrinsicHeight(BoxConstraints constraints) {
if (child == null)
return super.getMinIntrinsicHeight(constraints);
return getIntrinsicDimensions(constraints).height;
}
double getMaxIntrinsicHeight(BoxConstraints constraints) {
if (child == null)
return super.getMaxIntrinsicHeight(constraints);
return getIntrinsicDimensions(constraints).height;
}
Size getIntrinsicDimensions(BoxConstraints constraints) {
assert(child is RenderSector);
assert(child.parentData is SectorParentData);
assert(!constraints.isInfinite);
double maxChildDeltaRadius = math.min(constraints.maxWidth, constraints.maxHeight) / 2.0 - innerRadius;
SectorDimensions childDimensions = child.getIntrinsicDimensions(new SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), innerRadius);
double dimension = (innerRadius + childDimensions.deltaRadius) * 2.0;
return constraints.constrain(new Size(dimension, dimension));
}
void performLayout() {
if (child == null) {
size = constraints.constrain(Size.zero);
} else {
assert(child is RenderSector);
assert(!constraints.isInfinite);
double maxChildDeltaRadius = math.min(constraints.maxWidth, constraints.maxHeight) / 2.0 - innerRadius;
assert(child.parentData is SectorParentData);
child.parentData.radius = innerRadius;
child.parentData.theta = 0.0;
child.layout(new SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), parentUsesSize: true);
double dimension = (innerRadius + child.deltaRadius) * 2.0;
size = constraints.constrain(new Size(dimension, dimension));
}
}
void paint(PaintingCanvas canvas, Offset offset) {
super.paint(canvas, offset);
if (child != null) {
Rect bounds = offset & size;
// we move the offset to the center of the circle for the RenderSectors
canvas.paintChild(child, bounds.center);
}
}
bool hitTest(HitTestResult result, { Point position }) {
double x = position.x;
double y = position.y;
if (child == null)
return false;
// translate to our origin
x -= size.width/2.0;
y -= size.height/2.0;
// convert to radius/theta
double radius = math.sqrt(x*x+y*y);
double theta = (math.atan2(x, -y) - math.PI/2.0) % kTwoPi;
if (radius < innerRadius)
return false;
if (radius >= innerRadius + child.deltaRadius)
return false;
if (theta > child.deltaTheta)
return false;
child.hitTest(result, radius: radius, theta: theta);
result.add(new BoxHitTestEntry(this, position));
return true;
}
}
class RenderSolidColor extends RenderDecoratedSector {
RenderSolidColor(Color backgroundColor, {
this.desiredDeltaRadius: double.INFINITY,
this.desiredDeltaTheta: kTwoPi
}) : this.backgroundColor = backgroundColor,
super(new BoxDecoration(backgroundColor: backgroundColor));
double desiredDeltaRadius;
double desiredDeltaTheta;
final Color backgroundColor;
SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) {
return new SectorDimensions.withConstraints(constraints, deltaTheta: desiredDeltaTheta);
}
void performLayout() {
deltaRadius = constraints.constrainDeltaRadius(desiredDeltaRadius);
deltaTheta = constraints.constrainDeltaTheta(desiredDeltaTheta);
}
void handleEvent(sky.Event event, HitTestEntry entry) {
if (event.type == 'pointerdown')
decoration = new BoxDecoration(backgroundColor: const Color(0xFFFF0000));
else if (event.type == 'pointerup')
decoration = new BoxDecoration(backgroundColor: backgroundColor);
}
}
RenderBox buildSectorExample() {
RenderSectorRing rootCircle = new RenderSectorRing(padding: 20.0);
rootCircle.add(new RenderSolidColor(const Color(0xFF00FFFF), desiredDeltaTheta: kTwoPi * 0.15));
rootCircle.add(new RenderSolidColor(const Color(0xFF0000FF), desiredDeltaTheta: kTwoPi * 0.4));
RenderSectorSlice stack = new RenderSectorSlice(padding: 2.0);
stack.add(new RenderSolidColor(const Color(0xFFFFFF00), desiredDeltaRadius: 20.0));
stack.add(new RenderSolidColor(const Color(0xFFFF9000), desiredDeltaRadius: 20.0));
stack.add(new RenderSolidColor(const Color(0xFF00FF00)));
rootCircle.add(stack);
return new RenderBoxToRenderSectorAdapter(innerRadius: 50.0, child: rootCircle);
}
void main() {
new SkyBinding(root: buildSectorExample());
}

View File

@@ -0,0 +1,29 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:sky/theme/colors.dart';
import 'package:sky/theme/shadows.dart';
void main() {
var coloredBox = new RenderDecoratedBox(
decoration: new BoxDecoration(
gradient: new RadialGradient(
center: Point.origin, radius: 500.0,
colors: [Yellow[500], Blue[500]]),
boxShadow: shadows[3])
);
var paddedBox = new RenderPadding(
padding: const EdgeDims.all(50.0),
child: coloredBox);
new SkyBinding(root: new RenderDecoratedBox(
decoration: const BoxDecoration(
backgroundColor: const Color(0xFFFFFFFF)
),
child: paddedBox
));
}

View File

@@ -0,0 +1,65 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:sky/rendering/auto_layout.dart';
import 'package:cassowary/cassowary.dart' as al;
void main() {
RenderDecoratedBox c1 = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFF0000))
);
RenderDecoratedBox c2 = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFF00FF00))
);
RenderDecoratedBox c3 = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFF0000FF))
);
RenderDecoratedBox c4 = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF))
);
RenderAutoLayout root = new RenderAutoLayout(children: [c1, c2, c3, c4]);
AutoLayoutParentData p1 = c1.parentData;
AutoLayoutParentData p2 = c2.parentData;
AutoLayoutParentData p3 = c3.parentData;
AutoLayoutParentData p4 = c4.parentData;
root.addConstraints(<al.Constraint>[
// Sum of widths of each box must be equal to that of the container
(p1.width + p2.width + p3.width == root.width) as al.Constraint,
// The boxes must be stacked left to right
p1.rightEdge <= p2.leftEdge,
p2.rightEdge <= p3.leftEdge,
// The widths of the first and the third boxes should be equal
(p1.width == p3.width) as al.Constraint,
// The width of the second box should be twice as much as that of the first
// and third
(p2.width * al.cm(2.0) == p1.width) as al.Constraint,
// The height of the three boxes should be equal to that of the container
(p1.height == p2.height) as al.Constraint,
(p2.height == p3.height) as al.Constraint,
(p3.height == root.height) as al.Constraint,
// The fourth box should be half as wide as the second and must be attached
// to the right edge of the same (by its center)
(p4.width == p2.width / al.cm(2.0)) as al.Constraint,
(p4.height == al.cm(50.0)) as al.Constraint,
(p4.horizontalCenter == p2.rightEdge) as al.Constraint,
(p4.verticalCenter == p2.height / al.cm(2.0)) as al.Constraint,
]);
new SkyBinding(root: root);
}

View File

@@ -0,0 +1,51 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/box.dart';
class RenderSolidColorBox extends RenderDecoratedBox {
final Size desiredSize;
final Color backgroundColor;
RenderSolidColorBox(Color backgroundColor, { this.desiredSize: Size.infinite })
: backgroundColor = backgroundColor,
super(decoration: new BoxDecoration(backgroundColor: backgroundColor));
double getMinIntrinsicWidth(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.width
);
}
double getMaxIntrinsicWidth(BoxConstraints constraints) {
return constraints.constrainWidth(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.width
);
}
double getMinIntrinsicHeight(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.height
);
}
double getMaxIntrinsicHeight(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.height
);
}
void performLayout() {
size = constraints.constrain(desiredSize);
}
void handleEvent(sky.Event event, BoxHitTestEntry entry) {
if (event.type == 'pointerdown')
decoration = new BoxDecoration(backgroundColor: const Color(0xFFFF0000));
else if (event.type == 'pointerup')
decoration = new BoxDecoration(backgroundColor: backgroundColor);
}
}

View File

@@ -0,0 +1,49 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/base/scheduler.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:vector_math/vector_math.dart';
import 'solid_color_box.dart';
double timeBase;
RenderTransform transformBox;
void main() {
RenderFlex flexRoot = new RenderFlex(direction: FlexDirection.vertical);
void addFlexChildSolidColor(RenderFlex parent, sky.Color backgroundColor, { int flex: 0 }) {
RenderSolidColorBox child = new RenderSolidColorBox(backgroundColor);
parent.add(child);
child.parentData.flex = flex;
}
addFlexChildSolidColor(flexRoot, const sky.Color(0xFFFF00FF), flex: 1);
addFlexChildSolidColor(flexRoot, const sky.Color(0xFFFFFF00), flex: 2);
addFlexChildSolidColor(flexRoot, const sky.Color(0xFF00FFFF), flex: 1);
transformBox = new RenderTransform(child: flexRoot, transform: new Matrix4.identity());
RenderPadding root = new RenderPadding(padding: new EdgeDims.all(20.0), child: transformBox);
new SkyBinding(root: root);
addPersistentFrameCallback(rotate);
}
void rotate(double timeStamp) {
if (timeBase == null)
timeBase = timeStamp;
double delta = (timeStamp - timeBase) / 1000; // radians
transformBox.setIdentity();
transformBox.translate(transformBox.size.width / 2.0, transformBox.size.height / 2.0);
transformBox.rotateZ(delta);
transformBox.translate(-transformBox.size.width / 2.0, -transformBox.size.height / 2.0);
}

View File

@@ -0,0 +1,91 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/rendering/paragraph.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:sky/rendering/stack.dart';
import 'package:sky/theme/colors.dart';
// Material design colors. :p
List<Color> colors = [
Teal[500],
Amber[500],
Purple[500],
LightBlue[500],
DeepPurple[500],
Lime[500],
];
class Dot {
final Paint _paint;
Point position = Point.origin;
double radius = 0.0;
Dot({ Color color }) : _paint = new Paint()..color = color;
void update(sky.PointerEvent event) {
position = new Point(event.x, event.y);
radius = 5 + (95 * event.pressure);
}
void paint(PaintingCanvas canvas, Offset offset) {
canvas.drawCircle(position + offset, radius, _paint);
}
}
class RenderTouchDemo extends RenderBox {
Map<int, Dot> dots = new Map();
RenderTouchDemo();
void handleEvent(sky.Event event, BoxHitTestEntry entry) {
if (event is sky.PointerEvent) {
switch (event.type) {
case 'pointerdown':
Color color = colors[event.pointer.remainder(colors.length)];
dots[event.pointer] = new Dot(color: color)..update(event);
break;
case 'pointerup':
dots.remove(event.pointer);
break;
case 'pointercancel':
dots = new Map();
break;
case 'pointermove':
dots[event.pointer].update(event);
break;
}
}
markNeedsPaint();
}
void performLayout() {
size = constraints.biggest;
}
void paint(PaintingCanvas canvas, Offset offset) {
Paint white = new Paint()
..color = const Color(0xFFFFFFFF);
canvas.drawRect(offset & size, white);
for (Dot dot in dots.values)
dot.paint(canvas, offset);
}
}
void main() {
var paragraph = new RenderParagraph(new InlineText("Touch me!"));
var stack = new RenderStack(children: [
new RenderTouchDemo(),
paragraph,
]);
// Prevent the RenderParagraph from filling the whole screen so
// that it doesn't eat events.
paragraph.parentData..top = 40.0
..left = 20.0;
new SkyBinding(root: stack);
}

View File

@@ -0,0 +1,29 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/rendering/sky_binding.dart';
import 'package:vector_math/vector_math.dart';
void main() {
RenderDecoratedBox green = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const sky.Color(0xFF00FF00))
);
RenderConstrainedBox box = new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tight(const sky.Size(200.0, 200.0)),
child: green
);
Matrix4 transform = new Matrix4.identity();
RenderTransform spin = new RenderTransform(
transform: transform, child: box);
spin.rotateZ(1.0);
RenderFlex flex = new RenderFlex();
flex.add(spin);
new SkyBinding(root: flex);
}

View File

@@ -0,0 +1,14 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/sky_app.gni")
sky_app("stocks") {
main_dart = "lib/main.dart"
manifest = "sky.yaml"
if (is_android) {
apk_name = "Stocks"
}
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.domokit.stocks">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name="org.domokit.sky.shell.SkyApplication" android:label="Stocks">
<activity android:name="org.domokit.sky.shell.SkyActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
android:hardwareAccelerated="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More