Move example out of sky/packages to //examples

This commit is contained in:
Ian Fischer
2015-08-07 14:42:20 -07:00
parent 19fa9ae2d6
commit d44ed7dfc3
172 changed files with 51 additions and 51 deletions

28
examples/game/BUILD.gn Normal file
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("game") {
main_dart = "main.dart"
manifest = "sky.yaml"
if (is_android) {
apk_name = "Asteroids"
deps = [
"//examples/game/apk:resources",
]
} else if (is_ios) {
info_plist = "ios/Info.plist"
launcher_resources = [
"assets/Icon.png",
"assets/Icon@2x.png",
"ios/LaunchScreen.storyboardc",
]
} else if (is_mac) {
info_plist = "mac/Info.plist"
xibs = [ "mac/sky_mac.xib" ]
}
}

2
examples/game/README.md Normal file
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: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,147 @@
{"frames": [
{
"filename": "bar_shield.png",
"frame": {"x":2,"y":954,"w":412,"h":100},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":412,"h":100},
"sourceSize": {"w":412,"h":100},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "bar_shield_fill.png",
"frame": {"x":2,"y":1156,"w":320,"h":72},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":320,"h":72},
"sourceSize": {"w":320,"h":72},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "btn_play_down.png",
"frame": {"x":2,"y":484,"w":468,"h":468},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":2,"y":16,"w":468,"h":468},
"sourceSize": {"w":472,"h":484},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "btn_play_up.png",
"frame": {"x":2,"y":2,"w":468,"h":480},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":2,"y":4,"w":468,"h":480},
"sourceSize": {"w":472,"h":484},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_0.png",
"frame": {"x":416,"y":954,"w":38,"h":63},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_1.png",
"frame": {"x":324,"y":1221,"w":16,"h":57},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":45,"y":25,"w":16,"h":57},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_2.png",
"frame": {"x":366,"y":1056,"w":38,"h":63},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_3.png",
"frame": {"x":364,"y":1156,"w":35,"h":63},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":26,"y":22,"w":35,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_4.png",
"frame": {"x":416,"y":1019,"w":38,"h":57},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":25,"w":38,"h":57},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_5.png",
"frame": {"x":324,"y":1156,"w":38,"h":63},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_6.png",
"frame": {"x":406,"y":1078,"w":38,"h":63},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_7.png",
"frame": {"x":401,"y":1198,"w":35,"h":60},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":26,"y":22,"w":35,"h":60},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_8.png",
"frame": {"x":406,"y":1118,"w":38,"h":63},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_9.png",
"frame": {"x":401,"y":1158,"w":38,"h":63},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "scoreboard.png",
"frame": {"x":2,"y":1056,"w":362,"h":98},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":362,"h":98},
"sourceSize": {"w":362,"h":98},
"pivot": {"x":0.5,"y":0.5}
}],
"meta": {
"app": "http://www.codeandweb.com/texturepacker",
"version": "1.0",
"image": "game_ui.png",
"format": "RGBA8888",
"size": {"w":472,"h":1239},
"scale": "1",
"smartupdate": "$TexturePacker:SmartUpdate:02d6676bdde949110cbdc9a2c385b33a:6b0974f94eba9593dd9636cc730412b8:10ac111e32c27e51f4e8444dbb39eff6$"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 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,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<!--
This executable name must match the name of the app provided to the
ios_app GN template
-->
<key>CFBundleExecutable</key>
<string>game_app</string>
<key>CFBundleDisplayName</key>
<string>Asteroids</string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>CFBundleIdentifier</key>
<string>com.google.sky.game</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>game_app</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>DTPlatformName</key>
<string>iphonesimulator</string>
<key>DTSDKName</key>
<string>iphonesimulator8.3</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>MinimumOSVersion</key>
<string>8.3</string>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>iPhoneSimulator</string>
</array>
</dict>
</plist>

Binary file not shown.

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,61 @@
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);
}
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,12 @@
library game;
import 'dart:sky' as sky;
import 'dart:math' as Math;
import 'sprites.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/widgets/framework.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:vector_math/vector_math_64.dart';
part 'game_demo_world.dart';

View File

@@ -0,0 +1,744 @@
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;
SpriteSheet _spriteSheetUI;
Navigator _navigator;
// 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;
int _gameOverFrame;
int _currentLevel = 0;
// Heads up display
Hud _hud;
Function _gameOverCallback;
GameDemoWorld(App app, this._navigator, ImageMap images, this._spriteSheet, this._spriteSheetUI, this._gameOverCallback) : super(new Size(_gameSizeWidth, _gameSizeHeight)) {
// Fetch images
_imgNebula = images["assets/nebula.png"];
_gameLayer = new Node();
this.addChild(_gameLayer);
// 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;
_hud = new Hud(_spriteSheetUI);
_hud.zPosition = 1000.0;
addChild(_hud);
// Setup level
setupLevel(0);
}
void setupLevel(int level) {
int numLargeAsteroids = 5 + level * 2;
int numMediumAsteroids = 5 + level * 2;
// Add some asteroids to the game world
for (int i = 0; i < numLargeAsteroids; i++) {
addAsteroid(AsteroidSize.large);
}
for (int i = 0; i < numMediumAsteroids; i++) {
addAsteroid(AsteroidSize.medium);
}
_numFrames = 0;
_shield.visible = 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);
// Animate asteroid into the scene
Action action = new ActionTween((a) => asteroid.scale = a, 0.0, 1.0, 1.0, bounceOut);
_gameLayer.actions.run(action);
}
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);
// Scoring
if (asteroid._asteroidSize == AsteroidSize.large)
addScore(100);
else if (asteroid._asteroidSize == AsteroidSize.medium)
addScore(50);
else
addScore(10);
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();
// Check for level up
if (_asteroids.length == 0) {
_currentLevel++;
setupLevel(_currentLevel);
}
// Update shield
if (_numFrames > _numFramesShieldActive) _shield.visible = false;
else if (_numFrames > _numFramesShieldActive - _numFramesShieldFlickers) _shield.visible = !_shield.visible;
// Check for exit back to main screen
if (_isGameOver && _numFrames - _gameOverFrame == 60) {
_navigator.pop();
}
_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;
_gameOverFrame = _numFrames;
_gameOverCallback(_hud.score);
// 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;
}
// Scoring and HUD
void addScore(int score) {
_hud.score += score;
}
}
// 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 NodeWithSize {
sky.Image _image;
int _numStars;
bool _autoScroll;
List<Point> _starPositions;
List<double> _starScales;
List<Rect> _rects;
List<Color> _colors;
Paint _paint = new Paint()
..setFilterQuality(sky.FilterQuality.low)
..isAntiAlias = false
..setTransferMode(sky.TransferMode.plus);
StarField(SpriteSheet spriteSheet, this._numStars, [this._autoScroll = false]) : super(new Size(1024.0, 1024.0)) {
_starPositions = [];
_starScales = [];
_colors = [];
_rects = [];
for (int i = 0; i < _numStars; i++) {
_starPositions.add(new Point(_rand.nextDouble() * _gameSizeWidth, _rand.nextDouble() * _gameSizeHeight));
_starScales.add(_rand.nextDouble());
_colors.add(new Color.fromARGB((255.0 * (_rand.nextDouble() * 0.5 + 0.5)).toInt(), 255, 255, 255));
_rects.add(spriteSheet["star_${_rand.nextInt(2)}.png"].frame);
}
_image = spriteSheet.image;
}
void paint(PaintingCanvas canvas) {
// Create a transform for each star
List<sky.RSTransform> transforms = [];
for (int i = 0; i < _numStars; i++) {
sky.RSTransform transform = new sky.RSTransform(_starScales[i], 0.0, _starPositions[i].x, _starPositions[i].y);
transforms.add(transform);
}
// Draw the stars
canvas.drawAtlas(_image, transforms, _rects, _colors, sky.TransferMode.modulate, null, _paint);
}
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);
}
}
void update(double dt) {
if (_autoScroll) {
move(dt * 100.0, 0.0);
}
}
}
class Hud extends NodeWithSize {
SpriteSheet spriteSheetUI;
Sprite sprtBgScore;
Sprite sprtBgShield;
bool _dirtyScore = true;
int _score = 0;
int get score => _score;
set score(int score) {
_score = score;
_dirtyScore = true;
}
Hud(this.spriteSheetUI) {
pivot = Point.origin;
sprtBgScore = new Sprite(spriteSheetUI["scoreboard.png"]);
sprtBgScore.pivot = new Point(1.0, 0.0);
sprtBgScore.scale = 0.6;
addChild(sprtBgScore);
sprtBgShield = new Sprite(spriteSheetUI["bar_shield.png"]);
sprtBgShield.pivot = Point.origin;
sprtBgShield.scale = 0.6;
// TODO: Add shield
//addChild(sprtBgShield);
}
void spriteBoxPerformedLayout() {
// Set the size and position of HUD display
position = spriteBox.visibleArea.topLeft;
size = spriteBox.visibleArea.size;
// Position hud objects
sprtBgShield.position = new Point(20.0, 20.0);
sprtBgScore.position = new Point(size.width - 20.0, 20.0);
}
void update(double dt) {
// Update score
if (_dirtyScore) {
sprtBgScore.removeAllChildren();
String scoreStr = _score.toString();
double xPos = -50.0;
for (int i = scoreStr.length - 1; i >= 0; i--) {
String numStr = scoreStr.substring(i, i + 1);
Sprite numSprt = new Sprite(spriteSheetUI["number_$numStr.png"]);
numSprt.position = new Point(xPos, 49.0);
sprtBgScore.addChild(numSprt);
xPos -= 37.0;
}
_dirtyScore = false;
}
// Update power bar
}
}
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.transferMode = sky.TransferMode.plus;
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];
}

573
examples/game/lib/node.dart Normal file
View File

@@ -0,0 +1,573 @@
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;
double _skewX = 0.0;
double _skewY = 0.0;
/// The visibility of this node and its children.
bool visible = true;
double _zPosition = 0.0;
int _addedOrder;
int _childrenLastAddedOrder = 0;
bool _childrenNeedSorting = false;
Matrix4 _savedTotalMatrix;
/// 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();
if (_spriteBox != null) _spriteBox._actionControllers = null;
}
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();
}
double get skewX => _skewX;
void set skewX (double skewX) {
assert(skewX != null);
_skewX = skewX;
invalidateTransformMatrix();
}
double get skewY => _skewY;
void set skewY (double skewY) {
assert(skewY != null);
_skewY = skewY;
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._registerNode(child);
}
/// 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._deregisterNode(child);
}
}
/// 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._deregisterNode(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) {
_transformMatrix = computeTransformMatrix();
}
return _transformMatrix;
}
Matrix4 computeTransformMatrix() {
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
Matrix4 matrix = 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);
if (_skewX != 0.0 || _skewY != 0.0) {
// Needs skew transform
Matrix4 skew = new Matrix4(1.0, math.tan(radians(_skewX)), 0.0, 0.0,
math.tan(radians(_skewY)), 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
matrix.multiply(skew);
}
return matrix;
}
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, Matrix4 totalMatrix) {
assert(canvas != null);
if (!visible) return;
_prePaint(canvas, totalMatrix);
_visitChildren(canvas, totalMatrix);
_postPaint(canvas, totalMatrix);
}
void _prePaint(PaintingCanvas canvas, Matrix4 matrix) {
_savedTotalMatrix = new Matrix4.copy(matrix);
// Get the transformation matrix and apply transform
matrix.multiply(transformMatrix);
}
/// 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, Matrix4 totalMatrix) {
// 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, totalMatrix);
i++;
}
// Paint this node
canvas.setMatrix(totalMatrix.storage);
paint(canvas);
// Visit children in front of this node
while (i < _children.length) {
Node child = _children[i];
child._visit(canvas, totalMatrix);
i++;
}
}
void _postPaint(PaintingCanvas canvas, Matrix4 totalMatrix) {
totalMatrix.setFrom(_savedTotalMatrix);
}
// 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,49 @@
part of sprites;
class Node3D extends Node {
double _rotationX = 0.0;
double get rotationX => _rotationX;
set rotationX(double rotationX) {
_rotationX = rotationX;
invalidateTransformMatrix();
}
double _rotationY = 0.0;
double get rotationY => _rotationY;
set rotationY(double rotationY) {
_rotationY = rotationY;
invalidateTransformMatrix();
}
double _projectionDepth = 500.0;
double get projectionDepth => _projectionDepth;
set projectionDepth(double projectionDepth) {
_projectionDepth = projectionDepth;
invalidateTransformMatrix();
}
Matrix4 computeTransformMatrix() {
// Apply normal 2d transforms
Matrix4 matrix = super.computeTransformMatrix();
// Apply perspective projection
Matrix4 projection = new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, -1.0/_projectionDepth,
0.0, 0.0, 0.0, 1.0);
matrix = matrix.multiply(projection);
// Rotate around x and y axis
matrix.rotateY(radians(_rotationY));
matrix.rotateX(radians(_rotationX));
return matrix;
}
}

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,380 @@
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;
_ParticleAccelerations accelerations;
Float64List simpleColorSequence;
ColorSequence colorSequence;
}
class _ParticleAccelerations {
double radialAccel;
double tangentialAccel;
}
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;
int _numEmittedParticles = 0;
static Paint _paint = new Paint()
..setFilterQuality(FilterQuality.low)
..isAntiAlias = false;
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>();
_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) {
// TODO: Fix this (it's a temp fix for low framerates)
if (dt > 0.1) dt = 0.1;
// 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
if (particle.accelerations != null) {
// 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.accelerations.radialAccel);
// Tangential acceleration
double newY = tangential.x;
tangential.x = -tangential.y;
tangential.y = newY;
tangential.scale(particle.accelerations.tangentialAccel);
// (gravity + radial + tangential) * dt
Vector2 accel = (gravity + radial + tangential).scale(dt);
particle.dir += accel;
} else if (gravity[0] != 0.0 || gravity[1] != 0) {
// gravity
Vector2 accel = gravity.scale(dt);
particle.dir += accel;
}
// Update particle position
particle.pos[0] += particle.dir[0] * dt;
particle.pos[1] += particle.dir[1] * dt;
// Size
particle.size = math.max(particle.size + particle.deltaSize * dt, 0.0);
// Angle
particle.rotation += particle.deltaRotation * dt;
// Color
if (particle.simpleColorSequence != null) {
for (int i = 0; i < 4; i++) {
particle.simpleColorSequence[i] += particle.simpleColorSequence[i + 4] * dt;
}
} else {
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 * randomSignedDouble(), 0.0);
// Position
Point srcPos = Point.origin;
particle.pos = new Vector2(srcPos.x + posVar.x * randomSignedDouble(),
srcPos.y + posVar.y * randomSignedDouble());
// Size
particle.size = math.max(startSize + startSizeVar * randomSignedDouble(), 0.0);
double endSizeFinal = math.max(endSize + endSizeVar * randomSignedDouble(), 0.0);
particle.deltaSize = (endSizeFinal - particle.size) / particle.timeToLive;
// Rotation
particle.rotation = startRotation + startRotationVar * randomSignedDouble();
double endRotationFinal = endRotation + endRotationVar * randomSignedDouble();
particle.deltaRotation = (endRotationFinal - particle.rotation) / particle.timeToLive;
// Direction
double dirRadians = convertDegrees2Radians(direction + directionVar * randomSignedDouble());
Vector2 dirVector = new Vector2(math.cos(dirRadians), math.sin(dirRadians));
double speedFinal = speed + speedVar * randomSignedDouble();
particle.dir = dirVector.scale(speedFinal);
// Accelerations
if (radialAcceleration != 0.0 || radialAccelerationVar != 0.0 ||
tangentialAcceleration != 0.0 || tangentialAccelerationVar != 0.0) {
particle.accelerations = new _ParticleAccelerations();
// Radial acceleration
particle.accelerations.radialAccel = radialAcceleration + radialAccelerationVar * randomSignedDouble();
// Tangential acceleration
particle.accelerations.tangentialAccel = tangentialAcceleration + tangentialAccelerationVar * randomSignedDouble();
}
// Color
particle.colorPos = 0.0;
particle.deltaColorPos = 1.0 / particle.timeToLive;
if (alphaVar != 0 || redVar != 0 || greenVar != 0 || blueVar != 0) {
particle.colorSequence = _ColorSequenceUtil.copyWithVariance(colorSequence, alphaVar, redVar, greenVar, blueVar);
}
// Optimizes the case where there are only two colors in the sequence
if (colorSequence.colors.length == 2) {
Color startColor;
Color endColor;
if (particle.colorSequence != null) {
startColor = particle.colorSequence.colors[0];
endColor = particle.colorSequence.colors[1];
} else {
startColor = colorSequence.colors[0];
endColor = colorSequence.colors[1];
}
// First 4 elements are start ARGB, last 4 are delta ARGB
particle.simpleColorSequence = new Float64List(8);
particle.simpleColorSequence[0] = startColor.alpha.toDouble();
particle.simpleColorSequence[1] = startColor.red.toDouble();
particle.simpleColorSequence[2] = startColor.green.toDouble();
particle.simpleColorSequence[3] = startColor.blue.toDouble();
particle.simpleColorSequence[4] = (endColor.alpha.toDouble() - startColor.alpha.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[5] = (endColor.red.toDouble() - startColor.red.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[6] = (endColor.green.toDouble() - startColor.green.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[7] = (endColor.blue.toDouble() - startColor.blue.toDouble()) / particle.timeToLive;
}
_particles.add(particle);
_numEmittedParticles++;
}
void paint(PaintingCanvas canvas) {
List<RSTransform> transforms = [];
List<Rect> rects = [];
List<Color> colors = [];
_paint.setTransferMode(transferMode);
for (_Particle particle in _particles) {
// Rect
Rect rect = texture.frame;
rects.add(rect);
// Transform
double scos;
double ssin;
if (rotateToMovement) {
double extraRotation = GameMath.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 if (particle.rotation != 0.0) {
scos = math.cos(convertDegrees2Radians(particle.rotation)) * particle.size;
ssin = math.sin(convertDegrees2Radians(particle.rotation)) * particle.size;
} else {
scos = particle.size;
ssin = 0.0;
}
double ax = rect.width / 2;
double ay = rect.height / 2;
double tx = particle.pos[0] + -scos * ax + ssin * ay;
double ty = particle.pos[1] + -ssin * ax - scos * ay;
RSTransform transform = new RSTransform(scos, ssin, tx, ty);
transforms.add(transform);
// Color
if (particle.simpleColorSequence != null) {
Color particleColor = new Color.fromARGB(
particle.simpleColorSequence[0].toInt().clamp(0, 255),
particle.simpleColorSequence[1].toInt().clamp(0, 255),
particle.simpleColorSequence[2].toInt().clamp(0, 255),
particle.simpleColorSequence[3].toInt().clamp(0, 255));
colors.add(particleColor);
} else {
Color particleColor;
if (particle.colorSequence != null) {
particleColor = particle.colorSequence.colorAtPosition(particle.colorPos);
} else {
particleColor = colorSequence.colorAtPosition(particle.colorPos);
}
colors.add(particleColor);
}
}
canvas.drawAtlas(texture.image, transforms, rects, colors,
TransferMode.modulate, null, _paint);
}
}
class _ColorSequenceUtil {
static ColorSequence copyWithVariance(
ColorSequence sequence,
int alphaVar,
int redVar,
int greenVar,
int blueVar
) {
ColorSequence copy = new ColorSequence.copy(sequence);
int i = 0;
for (Color color in sequence.colors) {
int aDelta = ((randomDouble() * 2.0 - 1.0) * alphaVar).toInt();
int rDelta = ((randomDouble() * 2.0 - 1.0) * redVar).toInt();
int gDelta = ((randomDouble() * 2.0 - 1.0) * greenVar).toInt();
int bDelta = ((randomDouble() * 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);
copy.colors[i] = new Color.fromARGB(aNew, rNew, gNew, bNew);
i++;
}
return copy;
}
}

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;
Paint _cachedPaint = new Paint()
..setFilterQuality(FilterQuality.low)
..isAntiAlias = false;
/// 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) {
// 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
_cachedPaint.color = new Color.fromARGB((255.0*_opacity).toInt(), 255, 255, 255);
if (colorOverlay != null) {
_cachedPaint.setColorFilter(new ColorFilter.mode(colorOverlay, TransferMode.srcATop));
}
if (transferMode != null) {
_cachedPaint.setTransferMode(transferMode);
}
// Do actual drawing of the sprite
texture.drawTexture(canvas, Point.origin, _cachedPaint);
} else {
// Paint a red square for missing texture
canvas.drawRect(new Rect.fromLTRB(0.0, 0.0, size.width, size.height),
new Paint()..color = new Color.fromARGB(255, 255, 0, 0));
}
}
}

View File

@@ -0,0 +1,473 @@
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;
void set rootNode (NodeWithSize value) {
if (value == _rootNode) return;
// Ensure that the root node has a size
assert(value.size.width > 0);
assert(value.size.height > 0);
// Remove sprite box references
if (_rootNode != null) _removeSpriteBoxReference(_rootNode);
// Update the value
_rootNode = value;
// Add new references
_addSpriteBoxReference(_rootNode);
markNeedsLayout();
}
// Tracking of frame rate and updates
double _lastTimeStamp;
double _frameRate = 0.0;
double get frameRate => _frameRate;
// Transformation mode
SpriteBoxTransformMode _transformMode;
void set transformMode (SpriteBoxTransformMode value) {
if (value == _transformMode)
return;
_transformMode = value;
// Invalidate stuff
markNeedsLayout();
}
/// The transform mode used by the [SpriteBox].
SpriteBoxTransformMode get transformMode => _transformMode;
// Cached transformation matrix
Matrix4 _transformMatrix;
List<Node> _eventTargets;
List<ActionController> _actionControllers;
Rect _visibleArea;
Rect get visibleArea {
if (_visibleArea == null)
_calcTransformMatrix();
return _visibleArea;
}
// 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
this.rootNode = rootNode;
// Setup transform mode
this.transformMode = mode;
}
void _removeSpriteBoxReference(Node node) {
node._spriteBox = null;
for (Node child in node._children) {
_removeSpriteBoxReference(child);
}
}
void _addSpriteBoxReference(Node node) {
node._spriteBox = this;
for (Node child in node._children) {
_addSpriteBoxReference(child);
}
}
void attach() {
super.attach();
_scheduleTick();
}
// 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);
}
// Adding and removing nodes
_registerNode(Node node) {
_actionControllers = null;
_eventTargets = null;
}
_deregisterNode(Node node) {
_actionControllers = null;
_eventTargets = null;
}
// 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++;
}
}
EventDisposition handleEvent(Event event, _SpriteBoxHitTestEntry entry) {
if (!attached)
return EventDisposition.ignored;
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;
}
}
}
return EventDisposition.ignored;
}
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) {
_calcTransformMatrix();
}
return _transformMatrix;
}
void _calcTransformMatrix() {
_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;
}
_visibleArea = new Rect.fromLTRB(-offsetX / scaleX,
-offsetY / scaleY,
systemWidth + offsetX / scaleX,
systemHeight + offsetY / scaleY);
_transformMatrix.translate(offsetX, offsetY);
_transformMatrix.scale(scaleX, scaleY);
}
void _invalidateTransformMatrix() {
_visibleArea = null;
_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
Matrix4 totalMatrix = new Matrix4.fromFloat32List(canvas.getTotalMatrix());
_rootNode._visit(canvas, totalMatrix);
canvas.restore();
}
// Updates
void _scheduleTick() {
scheduler.requestAnimationFrame(_tick);
}
void _tick(double timeStamp) {
if (!attached)
return;
// Calculate delta and frame rate
if (_lastTimeStamp == null) _lastTimeStamp = timeStamp;
double delta = (timeStamp - _lastTimeStamp) / 1000;
_lastTimeStamp = timeStamp;
_frameRate = 1.0/delta;
_runActions(delta);
_callUpdate(_rootNode, delta);
// Schedule next update
_scheduleTick();
// Make sure the node graph is redrawn
markNeedsPaint();
}
void _runActions(double dt) {
if (_actionControllers == null) {
_actionControllers = [];
_addActionControllers(_rootNode, _actionControllers);
}
for (ActionController actions in _actionControllers) {
actions.step(dt);
}
}
void _addActionControllers(Node node, List<ActionController> controllers) {
if (node._actions != null) controllers.add(node._actions);
for (int i = node.children.length - 1; i >= 0; i--) {
Node child = node.children[i];
_addActionControllers(child, controllers);
}
}
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,37 @@
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);
root.rootNode = rootNode;
root.transformMode = transformMode;
}
}

View File

@@ -0,0 +1,33 @@
// 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:typed_data';
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/framework.dart';
import 'package:vector_math/vector_math.dart';
part 'action.dart';
part 'color_secuence.dart';
part 'image_map.dart';
part 'node.dart';
part 'node3d.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,112 @@
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) {
// Get drawing position
double x = position.x;
double y = position.y;
// Draw the texture
if (rotated) {
// Account for position
bool translate = (x != 0 || y != 0);
if (translate) {
canvas.translate(x, y);
}
// 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);
// Translate back
if (translate) {
canvas.translate(-x, -y);
}
} else {
// Draw the sprite
Rect dstRect = new Rect.fromLTWH(x + spriteSourceSize.left, y + spriteSourceSize.top, spriteSourceSize.width, spriteSourceSize.height);
canvas.drawImageRect(image, frame, dstRect, paint);
}
}
}

View File

@@ -0,0 +1,83 @@
part of sprites;
math.Random _random = new math.Random();
// Random methods
double randomDouble() {
return _random.nextDouble();
}
double randomSignedDouble() {
return _random.nextDouble() * 2.0 - 1.0;
}
int randomInt(int max) {
return _random.nextInt(max);
}
// atan2
class _Atan2Constants {
_Atan2Constants() {
for (int i = 0; i <= size; i++) {
double f = i.toDouble() / size.toDouble();
ppy[i] = math.atan(f) * stretch / math.PI;
ppx[i] = stretch * 0.5 - ppy[i];
pny[i] = -ppy[i];
pnx[i] = ppy[i] - stretch * 0.5;
npy[i] = stretch - ppy[i];
npx[i] = ppy[i] + stretch * 0.5;
nny[i] = ppy[i] - stretch;
nnx[i] = -stretch * 0.5 - ppy[i];
}
}
static const int size = 1024;
static const double stretch = math.PI;
static const int ezis = -size;
final Float64List ppy = new Float64List(size + 1);
final Float64List ppx = new Float64List(size + 1);
final Float64List pny = new Float64List(size + 1);
final Float64List pnx = new Float64List(size + 1);
final Float64List npy = new Float64List(size + 1);
final Float64List npx = new Float64List(size + 1);
final Float64List nny = new Float64List(size + 1);
final Float64List nnx = new Float64List(size + 1);
}
class GameMath {
static final _Atan2Constants _atan2 = new _Atan2Constants();
static double atan2(double y, double x) {
if (x >= 0) {
if (y >= 0) {
if (x >= y)
return _atan2.ppy[(_Atan2Constants.size * y / x + 0.5).toInt()];
else
return _atan2.ppx[(_Atan2Constants.size * x / y + 0.5).toInt()];
} else {
if (x >= -y)
return _atan2.pny[(_Atan2Constants.ezis * y / x + 0.5).toInt()];
else
return _atan2.pnx[(_Atan2Constants.ezis * x / y + 0.5).toInt()];
}
} else {
if (y >= 0) {
if (-x >= y)
return _atan2.npy[(_Atan2Constants.ezis * y / x + 0.5).toInt()];
else
return _atan2.npx[(_Atan2Constants.ezis * x / y + 0.5).toInt()];
} else {
if (x <= y)
return _atan2.nny[(_Atan2Constants.size * y / x + 0.5).toInt()];
else
return _atan2.nnx[(_Atan2Constants.size * x / y + 0.5).toInt()];
}
}
}
}

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>game_app</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>org.domokit.sky.asteroids</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Asteroids</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>10.6</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2015 The Chromium Authors. All rights reserved.</string>
<key>NSMainNibFile</key>
<string>sky_mac</string>
<key>NSPrincipalClass</key>
<string>SkyApplication</string>
</dict>
</plist>

View File

@@ -0,0 +1,695 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="7702" systemVersion="14E46" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="7702"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="SkyApplication">
<connections>
<outlet property="delegate" destination="Voe-Tx-rLC" id="GzC-gU-4Uq"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customObject id="Voe-Tx-rLC" customClass="SkyAppDelegate">
<connections>
<outlet property="window" destination="QvC-M9-y7g" id="gIp-Ho-8D9"/>
</connections>
</customObject>
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
<menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
<items>
<menuItem title="Sky" id="1Xt-HY-uBw">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Sky" systemMenu="apple" id="uQy-DD-JDr">
<items>
<menuItem title="About Sky" id="5kV-Vb-QxS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="-1" id="Exp-CZ-Vem"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
<menuItem title="Services" id="NMo-om-nkz">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
<menuItem title="Hide Sky" keyEquivalent="h" id="Olw-nP-bQN">
<connections>
<action selector="hide:" target="-1" id="PnN-Uc-m68"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="-1" id="VT4-aY-XCT"/>
</connections>
</menuItem>
<menuItem title="Show All" id="Kd2-mp-pUS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unhideAllApplications:" target="-1" id="Dhg-Le-xox"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
<menuItem title="Quit Sky" keyEquivalent="q" id="4sb-4s-VLi">
<connections>
<action selector="terminate:" target="-1" id="Te7-pn-YzF"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="File" id="dMs-cI-mzQ">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="File" id="bib-Uj-vzu">
<items>
<menuItem title="New" keyEquivalent="n" id="Was-JA-tGl">
<connections>
<action selector="newDocument:" target="-1" id="4Si-XN-c54"/>
</connections>
</menuItem>
<menuItem title="Open…" keyEquivalent="o" id="IAo-SY-fd9">
<connections>
<action selector="openDocument:" target="-1" id="bVn-NM-KNZ"/>
</connections>
</menuItem>
<menuItem title="Open Recent" id="tXI-mr-wws">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Open Recent" systemMenu="recentDocuments" id="oas-Oc-fiZ">
<items>
<menuItem title="Clear Menu" id="vNY-rz-j42">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="clearRecentDocuments:" target="-1" id="Daa-9d-B3U"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="m54-Is-iLE"/>
<menuItem title="Close" keyEquivalent="w" id="DVo-aG-piG">
<connections>
<action selector="performClose:" target="-1" id="HmO-Ls-i7Q"/>
</connections>
</menuItem>
<menuItem title="Save…" keyEquivalent="s" id="pxx-59-PXV">
<connections>
<action selector="saveDocument:" target="-1" id="teZ-XB-qJY"/>
</connections>
</menuItem>
<menuItem title="Save As…" keyEquivalent="S" id="Bw7-FT-i3A">
<connections>
<action selector="saveDocumentAs:" target="-1" id="mDf-zr-I0C"/>
</connections>
</menuItem>
<menuItem title="Revert to Saved" id="KaW-ft-85H">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="revertDocumentToSaved:" target="-1" id="iJ3-Pv-kwq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="aJh-i4-bef"/>
<menuItem title="Page Setup…" keyEquivalent="P" id="qIS-W8-SiK">
<modifierMask key="keyEquivalentModifierMask" shift="YES" command="YES"/>
<connections>
<action selector="runPageLayout:" target="-1" id="Din-rz-gC5"/>
</connections>
</menuItem>
<menuItem title="Print…" keyEquivalent="p" id="aTl-1u-JFS">
<connections>
<action selector="print:" target="-1" id="qaZ-4w-aoO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Edit" id="5QF-Oa-p0T">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Edit" id="W48-6f-4Dl">
<items>
<menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
<connections>
<action selector="undo:" target="-1" id="M6e-cu-g7V"/>
</connections>
</menuItem>
<menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
<connections>
<action selector="redo:" target="-1" id="oIA-Rs-6OD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
<menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
<connections>
<action selector="cut:" target="-1" id="YJe-68-I9s"/>
</connections>
</menuItem>
<menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
<connections>
<action selector="copy:" target="-1" id="G1f-GL-Joy"/>
</connections>
</menuItem>
<menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
<connections>
<action selector="paste:" target="-1" id="UvS-8e-Qdg"/>
</connections>
</menuItem>
<menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="-1" id="cEh-KX-wJQ"/>
</connections>
</menuItem>
<menuItem title="Delete" id="pa3-QI-u2k">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="-1" id="0Mk-Ml-PaM"/>
</connections>
</menuItem>
<menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
<connections>
<action selector="selectAll:" target="-1" id="VNm-Mi-diN"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
<menuItem title="Find" id="4EN-yA-p0u">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Find" id="1b7-l0-nxx">
<items>
<menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
<connections>
<action selector="performFindPanelAction:" target="-1" id="cD7-Qs-BN4"/>
</connections>
</menuItem>
<menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="performFindPanelAction:" target="-1" id="WD3-Gg-5AJ"/>
</connections>
</menuItem>
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
<connections>
<action selector="performFindPanelAction:" target="-1" id="NDo-RZ-v9R"/>
</connections>
</menuItem>
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
<connections>
<action selector="performFindPanelAction:" target="-1" id="HOh-sY-3ay"/>
</connections>
</menuItem>
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
<connections>
<action selector="performFindPanelAction:" target="-1" id="U76-nv-p5D"/>
</connections>
</menuItem>
<menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
<connections>
<action selector="centerSelectionInVisibleArea:" target="-1" id="IOG-6D-g5B"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
<items>
<menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
<connections>
<action selector="showGuessPanel:" target="-1" id="vFj-Ks-hy3"/>
</connections>
</menuItem>
<menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
<connections>
<action selector="checkSpelling:" target="-1" id="fz7-VC-reM"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
<menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleContinuousSpellChecking:" target="-1" id="7w6-Qz-0kB"/>
</connections>
</menuItem>
<menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleGrammarChecking:" target="-1" id="muD-Qn-j4w"/>
</connections>
</menuItem>
<menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticSpellingCorrection:" target="-1" id="2lM-Qi-WAP"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Substitutions" id="9ic-FL-obx">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
<items>
<menuItem title="Show Substitutions" id="z6F-FW-3nz">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontSubstitutionsPanel:" target="-1" id="oku-mr-iSq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
<menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleSmartInsertDelete:" target="-1" id="3IJ-Se-DZD"/>
</connections>
</menuItem>
<menuItem title="Smart Quotes" id="hQb-2v-fYv">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticQuoteSubstitution:" target="-1" id="ptq-xd-QOA"/>
</connections>
</menuItem>
<menuItem title="Smart Dashes" id="rgM-f4-ycn">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDashSubstitution:" target="-1" id="oCt-pO-9gS"/>
</connections>
</menuItem>
<menuItem title="Smart Links" id="cwL-P1-jid">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticLinkDetection:" target="-1" id="Gip-E3-Fov"/>
</connections>
</menuItem>
<menuItem title="Data Detectors" id="tRr-pd-1PS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDataDetection:" target="-1" id="R1I-Nq-Kbl"/>
</connections>
</menuItem>
<menuItem title="Text Replacement" id="HFQ-gK-NFA">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticTextReplacement:" target="-1" id="DvP-Fe-Py6"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Transformations" id="2oI-Rn-ZJC">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Transformations" id="c8a-y6-VQd">
<items>
<menuItem title="Make Upper Case" id="vmV-6d-7jI">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="uppercaseWord:" target="-1" id="sPh-Tk-edu"/>
</connections>
</menuItem>
<menuItem title="Make Lower Case" id="d9M-CD-aMd">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowercaseWord:" target="-1" id="iUZ-b5-hil"/>
</connections>
</menuItem>
<menuItem title="Capitalize" id="UEZ-Bs-lqG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="capitalizeWord:" target="-1" id="26H-TL-nsh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Speech" id="xrE-MZ-jX0">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Speech" id="3rS-ZA-NoH">
<items>
<menuItem title="Start Speaking" id="Ynk-f8-cLZ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="startSpeaking:" target="-1" id="654-Ng-kyl"/>
</connections>
</menuItem>
<menuItem title="Stop Speaking" id="Oyz-dy-DGm">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="stopSpeaking:" target="-1" id="dX8-6p-jy9"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Format" id="jxT-CU-nIS">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Format" id="GEO-Iw-cKr">
<items>
<menuItem title="Font" id="Gi5-1S-RQB">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Font" systemMenu="font" id="aXa-aM-Jaq">
<items>
<menuItem title="Show Fonts" keyEquivalent="t" id="Q5e-8K-NDq">
<connections>
<action selector="orderFrontFontPanel:" target="YLy-65-1bz" id="WHr-nq-2xA"/>
</connections>
</menuItem>
<menuItem title="Bold" tag="2" keyEquivalent="b" id="GB9-OM-e27">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="hqk-hr-sYV"/>
</connections>
</menuItem>
<menuItem title="Italic" tag="1" keyEquivalent="i" id="Vjx-xi-njq">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="IHV-OB-c03"/>
</connections>
</menuItem>
<menuItem title="Underline" keyEquivalent="u" id="WRG-CD-K1S">
<connections>
<action selector="underline:" target="-1" id="FYS-2b-JAY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="5gT-KC-WSO"/>
<menuItem title="Bigger" tag="3" keyEquivalent="+" id="Ptp-SP-VEL">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="Uc7-di-UnL"/>
</connections>
</menuItem>
<menuItem title="Smaller" tag="4" keyEquivalent="-" id="i1d-Er-qST">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="HcX-Lf-eNd"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kx3-Dk-x3B"/>
<menuItem title="Kern" id="jBQ-r6-VK2">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Kern" id="tlD-Oa-oAM">
<items>
<menuItem title="Use Default" id="GUa-eO-cwY">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardKerning:" target="-1" id="6dk-9l-Ckg"/>
</connections>
</menuItem>
<menuItem title="Use None" id="cDB-IK-hbR">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffKerning:" target="-1" id="U8a-gz-Maa"/>
</connections>
</menuItem>
<menuItem title="Tighten" id="46P-cB-AYj">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="tightenKerning:" target="-1" id="hr7-Nz-8ro"/>
</connections>
</menuItem>
<menuItem title="Loosen" id="ogc-rX-tC1">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="loosenKerning:" target="-1" id="8i4-f9-FKE"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Ligatures" id="o6e-r0-MWq">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Ligatures" id="w0m-vy-SC9">
<items>
<menuItem title="Use Default" id="agt-UL-0e3">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardLigatures:" target="-1" id="7uR-wd-Dx6"/>
</connections>
</menuItem>
<menuItem title="Use None" id="J7y-lM-qPV">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffLigatures:" target="-1" id="iX2-gA-Ilz"/>
</connections>
</menuItem>
<menuItem title="Use All" id="xQD-1f-W4t">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useAllLigatures:" target="-1" id="KcB-kA-TuK"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Baseline" id="OaQ-X3-Vso">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Baseline" id="ijk-EB-dga">
<items>
<menuItem title="Use Default" id="3Om-Ey-2VK">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unscript:" target="-1" id="0vZ-95-Ywn"/>
</connections>
</menuItem>
<menuItem title="Superscript" id="Rqc-34-cIF">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="superscript:" target="-1" id="3qV-fo-wpU"/>
</connections>
</menuItem>
<menuItem title="Subscript" id="I0S-gh-46l">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="subscript:" target="-1" id="Q6W-4W-IGz"/>
</connections>
</menuItem>
<menuItem title="Raise" id="2h7-ER-AoG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="raiseBaseline:" target="-1" id="4sk-31-7Q9"/>
</connections>
</menuItem>
<menuItem title="Lower" id="1tx-W0-xDw">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowerBaseline:" target="-1" id="OF1-bc-KW4"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="Ndw-q3-faq"/>
<menuItem title="Show Colors" keyEquivalent="C" id="bgn-CT-cEk">
<connections>
<action selector="orderFrontColorPanel:" target="-1" id="mSX-Xz-DV3"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="iMs-zA-UFJ"/>
<menuItem title="Copy Style" keyEquivalent="c" id="5Vv-lz-BsD">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="copyFont:" target="-1" id="GJO-xA-L4q"/>
</connections>
</menuItem>
<menuItem title="Paste Style" keyEquivalent="v" id="vKC-jM-MkH">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteFont:" target="-1" id="JfD-CL-leO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Text" id="Fal-I4-PZk">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Text" id="d9c-me-L2H">
<items>
<menuItem title="Align Left" keyEquivalent="{" id="ZM1-6Q-yy1">
<connections>
<action selector="alignLeft:" target="-1" id="zUv-R1-uAa"/>
</connections>
</menuItem>
<menuItem title="Center" keyEquivalent="|" id="VIY-Ag-zcb">
<connections>
<action selector="alignCenter:" target="-1" id="spX-mk-kcS"/>
</connections>
</menuItem>
<menuItem title="Justify" id="J5U-5w-g23">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="alignJustified:" target="-1" id="ljL-7U-jND"/>
</connections>
</menuItem>
<menuItem title="Align Right" keyEquivalent="}" id="wb2-vD-lq4">
<connections>
<action selector="alignRight:" target="-1" id="r48-bG-YeY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="4s2-GY-VfK"/>
<menuItem title="Writing Direction" id="H1b-Si-o9J">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Writing Direction" id="8mr-sm-Yjd">
<items>
<menuItem title="Paragraph" enabled="NO" id="ZvO-Gk-QUH">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="YGs-j5-SAR">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionNatural:" target="-1" id="qtV-5e-UBP"/>
</connections>
</menuItem>
<menuItem id="Lbh-J2-qVU">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionLeftToRight:" target="-1" id="S0X-9S-QSf"/>
</connections>
</menuItem>
<menuItem id="jFq-tB-4Kx">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionRightToLeft:" target="-1" id="5fk-qB-AqJ"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="swp-gr-a21"/>
<menuItem title="Selection" enabled="NO" id="cqv-fj-IhA">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="Nop-cj-93Q">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionNatural:" target="-1" id="lPI-Se-ZHp"/>
</connections>
</menuItem>
<menuItem id="BgM-ve-c93">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionLeftToRight:" target="-1" id="caW-Bv-w94"/>
</connections>
</menuItem>
<menuItem id="RB4-Sm-HuC">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionRightToLeft:" target="-1" id="EXD-6r-ZUu"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="fKy-g9-1gm"/>
<menuItem title="Show Ruler" id="vLm-3I-IUL">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleRuler:" target="-1" id="FOx-HJ-KwY"/>
</connections>
</menuItem>
<menuItem title="Copy Ruler" keyEquivalent="c" id="MkV-Pr-PK5">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="copyRuler:" target="-1" id="71i-fW-3W2"/>
</connections>
</menuItem>
<menuItem title="Paste Ruler" keyEquivalent="v" id="LVM-kO-fVI">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="pasteRuler:" target="-1" id="cSh-wd-qM2"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="View" id="H8h-7b-M4v">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="View" id="HyV-fh-RgO">
<items>
<menuItem title="Show Toolbar" keyEquivalent="t" id="snW-S8-Cw5">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="toggleToolbarShown:" target="-1" id="BXY-wc-z0C"/>
</connections>
</menuItem>
<menuItem title="Customize Toolbar…" id="1UK-8n-QPP">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="runToolbarCustomizationPalette:" target="-1" id="pQI-g3-MTW"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Window" id="aUF-d1-5bR">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
<items>
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
<connections>
<action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>
</connections>
</menuItem>
<menuItem title="Zoom" id="R4o-n2-Eq4">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="performZoom:" target="-1" id="DIl-cC-cCs"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="wpr-3q-Mcd">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ">
<items>
<menuItem title="Sky Help" keyEquivalent="?" id="FKE-Sm-Kum">
<connections>
<action selector="showHelp:" target="-1" id="y7X-2Q-9no"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
<window title="Sky" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="SkyWindow">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="335" y="390" width="480" height="360"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1177"/>
<view key="contentView" id="EiT-Mj-1SZ">
<rect key="frame" x="0.0" y="0.0" width="480" height="360"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<openGLView autoresizesSubviews="NO" useAuxiliaryDepthBufferStencil="NO" useDoubleBufferingEnabled="YES" allowOffline="YES" translatesAutoresizingMaskIntoConstraints="NO" id="AUD-Hu-um3">
<rect key="frame" x="0.0" y="0.0" width="480" height="360"/>
</openGLView>
</subviews>
<constraints>
<constraint firstAttribute="trailing" secondItem="AUD-Hu-um3" secondAttribute="trailing" id="9W1-4Z-nsQ"/>
<constraint firstItem="AUD-Hu-um3" firstAttribute="top" secondItem="EiT-Mj-1SZ" secondAttribute="top" id="KpO-qK-Zhv"/>
<constraint firstAttribute="bottom" secondItem="AUD-Hu-um3" secondAttribute="bottom" id="Myy-UN-4eQ"/>
<constraint firstItem="AUD-Hu-um3" firstAttribute="leading" secondItem="EiT-Mj-1SZ" secondAttribute="leading" id="gf3-3r-c0N"/>
</constraints>
</view>
<connections>
<outlet property="renderSurface" destination="AUD-Hu-um3" id="0jv-sx-91g"/>
</connections>
<point key="canvasLocation" x="128" y="455"/>
</window>
</objects>
</document>

229
examples/game/main.dart Normal file
View File

@@ -0,0 +1,229 @@
// 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/rendering/object.dart';
import 'package:sky/painting/text_style.dart';
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/button_base.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/framework.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;
SpriteSheet _spriteSheetUI;
GameDemoApp _app;
main() async {
_loader = new ImageMap(_bundle);
await _loader.load([
'assets/nebula.png',
'assets/sprites.png',
'assets/starfield.png',
'assets/game_ui.png',
]);
String json = await _bundle.loadString('assets/sprites.json');
_spriteSheet = new SpriteSheet(_loader['assets/sprites.png'], json);
json = await _bundle.loadString('assets/game_ui.json');
_spriteSheetUI = new SpriteSheet(_loader["assets/game_ui.png"], json);
_app = new GameDemoApp();
runApp(_app);
}
class GameDemoApp extends App {
NavigationState _navigationState;
GameDemoWorld _game;
int _lastScore = 0;
void initState() {
_navigationState = new NavigationState([
new Route(
name: '/',
builder: _buildMainScene
),
new Route(
name: '/game',
builder: _buildGameScene
),
]);
super.initState();
}
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 Navigator(_navigationState)
)
);
}
Widget _buildGameScene(navigator, route) {
return new SpriteWidget(_game);
}
Widget _buildMainScene(navigator, route) {
return new Stack([
new SpriteWidget(new MainScreenBackground()),
new Flex([
new TextureButton(
onPressed: () {
_game = new GameDemoWorld(
_app,
navigator,
_loader,
_spriteSheet,
_spriteSheetUI,
(lastScore) {
setState(() {_lastScore = lastScore;});
}
);
navigator.pushNamed('/game');
},
texture: _spriteSheetUI["btn_play_up.png"],
textureDown: _spriteSheetUI["btn_play_down.png"],
width: 128.0,
height: 128.0
),
new Text(
"Last Score: $_lastScore",
style: new TextStyle(fontSize:20.0)
)
],
direction: FlexDirection.vertical,
justifyContent: FlexJustifyContent.center)
]);
}
}
class TextureButton extends ButtonBase {
TextureButton({
Key key,
this.onPressed,
this.texture,
this.textureDown,
this.width: 128.0,
this.height: 128.0
}) : super(key: key);
final Function onPressed;
final Texture texture;
final Texture textureDown;
final double width;
final double height;
Widget buildContent() {
return new Listener(
child: new Container(
width: width,
height: height,
child: new CustomPaint(
callback: paintCallback,
token: new _TextureButtonToken(
highlight,
texture,
textureDown,
width,
height
)
)
),
onPointerUp: (_) {
if (onPressed != null) onPressed();
}
);
}
void paintCallback(PaintingCanvas canvas, Size size) {
if (texture == null)
return;
canvas.save();
if (highlight && textureDown != null) {
// Draw down state
canvas.scale(size.width / textureDown.size.width, size.height / textureDown.size.height);
textureDown.drawTexture(canvas, Point.origin, new Paint());
} else {
// Draw up state
canvas.scale(size.width / texture.size.width, size.height / texture.size.height);
texture.drawTexture(canvas, Point.origin, new Paint());
}
canvas.restore();
}
}
class _TextureButtonToken {
_TextureButtonToken(
this._highlight,
this._texture,
this._textureDown,
this._width,
this._height
);
final bool _highlight;
final Texture _texture;
final Texture _textureDown;
final double _width;
final double _height;
bool operator== (other) {
return
other is _TextureButtonToken &&
_highlight == other._highlight &&
_texture == other._texture &&
_textureDown == other._textureDown &&
_width == other._width &&
_height == other._height;
}
int get hashCode {
int value = 373;
value = 37 * value * _highlight.hashCode;
value = 37 * value * _texture.hashCode;
value = 37 * value * _textureDown.hashCode;
value = 37 * value * _width.hashCode;
value = 37 * value * _height.hashCode;
return value;
}
}
class MainScreenBackground extends NodeWithSize {
MainScreenBackground() : super(new Size(1024.0, 1024.0)) {
Sprite sprtBackground = new Sprite.fromImage(_loader["assets/starfield.png"]);
sprtBackground.position = new Point(512.0, 512.0);
addChild(sprtBackground);
StarField starField = new StarField(_spriteSheet, 200, true);
addChild(starField);
}
}

7
examples/game/sky.yaml Normal file
View File

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

View File

@@ -0,0 +1,84 @@
import 'lib/sprites.dart';
import 'dart:sky';
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/theme.dart';
AssetBundle _initBundle() {
if (rootBundle != null)
return rootBundle;
return new NetworkAssetBundle(Uri.base);
}
final AssetBundle _bundle = _initBundle();
ImageMap _images;
SpriteSheet _spriteSheet;
TestDrawAtlasApp _app;
main() async {
_images = new ImageMap(_bundle);
await _images.load([
'assets/sprites.png'
]);
String json = await _bundle.loadString('assets/sprites.json');
_spriteSheet = new SpriteSheet(_images['assets/sprites.png'], json);
_app = new TestDrawAtlasApp();
runApp(_app);
}
class TestDrawAtlasApp extends App {
Widget build() {
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Purple
);
return new Theme(
data: theme,
child: new TaskDescription(
label: 'Test drawAtlas',
child: new SpriteWidget(
new TestDrawAtlas(),
SpriteBoxTransformMode.fixedWidth
)
)
);
}
}
class TestDrawAtlas extends NodeWithSize {
TestDrawAtlas() : super(new Size(1024.0, 1024.0)) {
}
void paint(PaintingCanvas canvas) {
List<RSTransform> transforms = [
new RSTransform(1.0, 0.0, 100.0, 100.0)
];
List<Rect> rects = [
_spriteSheet["ship.png"].frame
];
List<Color> colors = [
new Color(0xffffffff)
];
canvas.drawAtlas(
_spriteSheet.image,
transforms,
rects,
colors,
TransferMode.src,
null,
new Paint()..setFilterQuality(FilterQuality.low)..isAntiAlias=false
);
}
}

View File

@@ -0,0 +1,311 @@
import 'dart:sky' as sky;
import 'dart:math' as math;
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/theme.dart';
import 'lib/sprites.dart';
AssetBundle _initBundle() {
if (rootBundle != null)
return rootBundle;
return new NetworkAssetBundle(Uri.base);
}
final AssetBundle _bundle = _initBundle();
ImageMap _images;
SpriteSheet _spriteSheet;
TestApp _app;
main() async {
_images = new ImageMap(_bundle);
await _images.load([
'assets/sprites.png'
]);
String json = await _bundle.loadString('assets/sprites.json');
_spriteSheet = new SpriteSheet(_images['assets/sprites.png'], json);
_app = new TestApp();
runApp(_app);
}
class TestApp extends App {
Widget build() {
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Purple
);
return new Theme(
data: theme,
child: new TaskDescription(
label: 'Test Sprite Performance',
child: new SpriteWidget(new TestPerformance())
)
);
}
}
class TestPerformance extends NodeWithSize {
final int numFramesPerTest = 100;
final int numTests = 5;
TestPerformance() : super(new Size(1024.0, 1024.0)) {
}
int test = 0;
int frame = 0;
int testStartTime;
void update(double dt) {
if (frame % numFramesPerTest == 0) {
if (test > 0 && test <= numTests) {
// End last test
int currentTime = new DateTime.now().millisecondsSinceEpoch;
int totalTestTime = currentTime - testStartTime;
double millisPerFrame =
totalTestTime.toDouble() / numFramesPerTest.toDouble();
print(" - RESULT fps: ${(1.0 / (millisPerFrame / 1000)).toStringAsFixed(1)} millis/frame: ${millisPerFrame.round()}");
// Clear test
removeAllChildren();
}
if (test < numTests) {
// Start new test
PerformanceTest perfTest = createTest(test);
addChild(perfTest);
print("TEST ${test + 1}/$numTests STARTING: ${perfTest.name}");
testStartTime = new DateTime.now().millisecondsSinceEpoch;
}
test++;
}
frame++;
}
PerformanceTest createTest(int n) {
if (test == 0) {
// Test atlas performance
return new TestPerformanceAtlas();
} else if (test == 1) {
// Test atlas performance
return new TestPerformanceAtlas2();
} else if (test == 2) {
// Test sprite performance
return new TestPerformanceSprites();
} else if (test == 3) {
// Test sprite performance
return new TestPerformanceSprites2();
} else if (test == 4) {
// Test particle performance
return new TestPerformanceParticles();
}
return null;
}
}
abstract class PerformanceTest extends Node {
String get name;
}
class TestPerformanceParticles extends PerformanceTest {
String get name => "64 particle systems";
final grid = 8;
TestPerformanceParticles() {
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
ParticleSystem particles = 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,
emissionRate:100.0,
greenVar: 127,
redVar: 127
);
particles.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(particles);
}
}
}
}
class TestPerformanceSprites extends PerformanceTest {
String get name => "1001 sprites (24% offscreen)";
final int grid = 100;
TestPerformanceSprites() {
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.scale = 1.0;
sprt.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprt);
//sprt.actions.run(new ActionRepeatForever(new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 1.0)));
}
}
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.position = new Point(512.0, 512.0);
addChild(sprt);
}
void update(double dt) {
for (Sprite sprt in children) {
sprt.rotation += 1;
}
}
}
class TestPerformanceSprites2 extends PerformanceTest {
String get name => "1001 sprites (24% offscreen never added)";
final int grid = 100;
TestPerformanceSprites2() {
for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) {
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.scale = 1.0;
sprt.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprt);
//sprt.actions.run(new ActionRepeatForever(new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 1.0)));
}
}
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.position = new Point(512.0, 512.0);
addChild(sprt);
}
void update(double dt) {
for (Sprite sprt in children) {
sprt.rotation += 1;
}
}
}
class TestPerformanceAtlas extends PerformanceTest {
String get name => "1001 rects drawAtlas (24% offscreen)";
final int grid = 100;
double rotation = 0.0;
List<Rect> rects = [];
Paint cachedPaint = new Paint()
..setFilterQuality(sky.FilterQuality.low)
..isAntiAlias = false;
TestPerformanceAtlas() {
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
rects.add(_spriteSheet["asteroid_big_1.png"].frame);
}
}
rects.add(_spriteSheet["asteroid_big_1.png"].frame);
}
void paint(PaintingCanvas canvas) {
// Setup transforms
List<sky.RSTransform> transforms = [];
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
double xPos = x * 1024.0 / (grid - 1);
double yPos = y * 1024.0 / (grid - 1);
transforms.add(createTransform(xPos, yPos, rects[0].size.width / 2.0, rects[0].size.height / 2.0, rotation, 1.0));
}
}
transforms.add(createTransform(512.0, 512.0, rects[0].size.width / 2.0, rects[0].size.height / 2.0, rotation, 1.0));
// Draw atlas
Rect cullRect = spriteBox.visibleArea;
canvas.drawAtlas(_spriteSheet.image, transforms, rects, null, null, cullRect, cachedPaint);
}
void update(double dt) {
rotation += 1.0;
}
sky.RSTransform createTransform(double x, double y, double ax, double ay, double rot, double scale) {
double scos = math.cos(convertDegrees2Radians(rot)) * scale;
double ssin = math.sin(convertDegrees2Radians(rot)) * scale;
double tx = x + -scos * ax + ssin * ay;
double ty = y + -ssin * ax - scos * ay;
return new sky.RSTransform(scos, ssin, tx, ty);
}
}
class TestPerformanceAtlas2 extends PerformanceTest {
String get name => "1001 rects drawAtlas (24% offscreen never added)";
final int grid = 100;
double rotation = 0.0;
List<Rect> rects = [];
Paint cachedPaint = new Paint()
..setFilterQuality(sky.FilterQuality.low)
..isAntiAlias = false;
TestPerformanceAtlas2() {
for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) {
rects.add(_spriteSheet["asteroid_big_1.png"].frame);
}
}
rects.add(_spriteSheet["asteroid_big_1.png"].frame);
}
void paint(PaintingCanvas canvas) {
// Setup transforms
List<sky.RSTransform> transforms = [];
for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) {
double xPos = x * 1024.0 / (grid - 1);
double yPos = y * 1024.0 / (grid - 1);
transforms.add(createTransform(xPos, yPos, rects[0].size.width / 2.0, rects[0].size.height / 2.0, rotation, 1.0));
}
}
transforms.add(createTransform(512.0, 512.0, rects[0].size.width / 2.0, rects[0].size.height / 2.0, rotation, 1.0));
// Draw atlas
Rect cullRect = spriteBox.visibleArea;
canvas.drawAtlas(_spriteSheet.image, transforms, rects, null, null, cullRect, cachedPaint);
}
void update(double dt) {
rotation += 1.0;
}
sky.RSTransform createTransform(double x, double y, double ax, double ay, double rot, double scale) {
double scos = math.cos(convertDegrees2Radians(rot)) * scale;
double ssin = math.sin(convertDegrees2Radians(rot)) * scale;
double tx = x + -scos * ax + ssin * ay;
double ty = y + -ssin * ax - scos * ay;
return new sky.RSTransform(scos, ssin, tx, ty);
}
}

View File

@@ -0,0 +1,309 @@
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:vector_math/vector_math.dart';
main() {
runTest();
}
const int numSystems = 1000;
const int numFrames = 1000;
void runTest() {
int timeStart;
timeStart = new DateTime.now().millisecondsSinceEpoch;
// Create systems
List<TestParticleSystem> systems = [];
for (int i = 0; i < numSystems; i++) {
systems.add(new TestParticleSystem());
}
int timeAfterCreate = new DateTime.now().millisecondsSinceEpoch;
print("TIME creation ${(timeAfterCreate - timeStart) / 1000.0}");
timeStart = new DateTime.now().millisecondsSinceEpoch;
// Update systems
for (int frame = 0; frame < numFrames; frame++) {
for (int i = 0; i < numSystems; i++) {
systems[i].update(1.0 / 60.0);
}
}
int timeAfterUpdates = new DateTime.now().millisecondsSinceEpoch;
print("TIME updates ${(timeAfterUpdates - timeStart) / 1000.0}");
timeStart = new DateTime.now().millisecondsSinceEpoch;
// Calculate matrices
for (int frame = 0; frame < numFrames; frame++) {
for (int i = 0; i < numSystems; i++) {
systems[i].paint();
}
}
int timeAfterMatrices = new DateTime.now().millisecondsSinceEpoch;
print("TIME matrices ${(timeAfterMatrices - timeStart) / 1000.0}");
}
class TestParticle {
Vector2 pos;
Vector2 startPos;
double colorPos;
double deltaColorPos;
double size;
double deltaSize;
double rotation;
double deltaRotation;
double timeToLive;
Vector2 dir;
double radialAccel;
double tangentialAccel;
Float64List simpleColorSequence;
Matrix4 transform;
}
class TestParticleSystem {
double life;
double lifeVar;
Vector2 posVar;
double startSize;
double startSizeVar;
double endSize;
double endSizeVar;
double startRotation;
double startRotationVar;
double endRotation;
double endRotationVar;
double direction;
double directionVar;
double speed;
double speedVar;
double radialAcceleration;
double radialAccelerationVar;
double tangentialAcceleration;
double tangentialAccelerationVar;
Vector2 gravity;
int maxParticles;
int numParticlesToEmit;
double emissionRate;
List<TestParticle> _particles;
double _emitCounter;
int _numEmittedParticles = 0;
TestParticleSystem({this.life: 1.5,
this.lifeVar: 0.0,
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.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.numParticlesToEmit: 0}) {
posVar = new Vector2.zero();
_particles = new List<TestParticle>();
_emitCounter = 0.0;
gravity = new Vector2.zero();
}
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;
}
// Iterate over all particles
for (int i = _particles.length -1; i >= 0; i--) {
TestParticle 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;
// Update particle position
particle.pos[0] += particle.dir[0] * dt;
particle.pos[1] += particle.dir[1] * dt;
// Size
particle.size = math.max(particle.size + particle.deltaSize * dt, 0.0);
// Angle
particle.rotation += particle.deltaRotation * dt;
// Color
if (particle.simpleColorSequence != null) {
for (int i = 0; i < 4; i++) {
particle.simpleColorSequence[i] += particle.simpleColorSequence[i + 4] * dt;
}
} else {
particle.colorPos = math.min(particle.colorPos + particle.deltaColorPos * dt, 1.0);
}
}
}
void _addParticle() {
TestParticle particle = new TestParticle();
// Time to live
particle.timeToLive = math.max(life + lifeVar * randomSignedDouble(), 0.0);
// Position
Vector2 srcPos = new Vector2.zero();
particle.pos = new Vector2(srcPos.x + posVar.x * randomSignedDouble(),
srcPos.y + posVar.y * randomSignedDouble());
// Size
particle.size = math.max(startSize + startSizeVar * randomSignedDouble(), 0.0);
double endSizeFinal = math.max(endSize + endSizeVar * randomSignedDouble(), 0.0);
particle.deltaSize = (endSizeFinal - particle.size) / particle.timeToLive;
// Rotation
particle.rotation = startRotation + startRotationVar * randomSignedDouble();
double endRotationFinal = endRotation + endRotationVar * randomSignedDouble();
particle.deltaRotation = (endRotationFinal - particle.rotation) / particle.timeToLive;
// Direction
double dirRadians = radians(direction + directionVar * randomSignedDouble());
Vector2 dirVector = new Vector2(math.cos(dirRadians), math.sin(dirRadians));
double speedFinal = speed + speedVar * randomSignedDouble();
particle.dir = dirVector.scale(speedFinal);
// Radial acceleration
particle.radialAccel = radialAcceleration + radialAccelerationVar * randomSignedDouble();
// Tangential acceleration
particle.tangentialAccel = tangentialAcceleration + tangentialAccelerationVar * randomSignedDouble();
// Colors
particle.simpleColorSequence = new Float64List(8);
particle.simpleColorSequence[0] = 255.0;
particle.simpleColorSequence[1] = 255.0;
particle.simpleColorSequence[2] = 255.0;
particle.simpleColorSequence[3] = 255.0;
particle.simpleColorSequence[4] = 255.0;
particle.simpleColorSequence[5] = 0.0;
particle.simpleColorSequence[6] = 0.0;
particle.simpleColorSequence[7] = 0.0;
// Transform
particle.transform = new Matrix4.identity();
// Add particle
_particles.add(particle);
_numEmittedParticles++;
}
void paint() {
if (!printed) {
printed = true;
}
for (int i = _particles.length -1; i >= 0; i--) {
TestParticle particle = _particles[i];
particle.rotation + randomSignedDouble();
// Transform
double c = math.cos(radians(particle.rotation));
double s = math.sin(radians(particle.rotation));
// Create transformation matrix for scale, position and rotation
Matrix4 matrix = new Matrix4(c * particle.size, s * particle.size, 0.0, 0.0,
-s * particle.size, c * particle.size, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
particle.pos.x, particle.pos.y, 0.0, 1.0);
particle.transform.multiply(matrix);
}
}
}
math.Random _random = new math.Random();
bool printed = false;
// Random methods
double randomDouble() {
return _random.nextDouble();
}
double randomSignedDouble() {
return _random.nextDouble() * 2.0 - 1.0;
}
int randomInt(int max) {
return _random.nextInt(max);
}