Photo Album
A framed photo viewer with a scrolling, magnifying strip of thumbnails.
What you are seeing
A large landscape photograph in a thick white frame fills a dark panel. When the pointer nears the bottom, a strip of tilted thumbnails rises, with the middle thumbnails enlarged.
How it works
A sensor rectangle at the bottom of the demo slides the thumbnail strip into view.
A second sensor turns the distance from the center of the strip into a scrolling speed.
The magnifier enlarges the thumbnails at the middle of the strip as it scrolls.
A local source now supplies 48 generated pictures through the original photo source interface.
History
Posted on October 4, 2009, as an example of an AJAX style application written in SVG.
Source
/photoAlbum/album.svg
<?xml version="1.0" encoding="UTF-8"?>
<!-- ======================================================================= -->
<!-- Vincent Hardy -->
<!-- License terms: see svg-wow.org -->
<!-- CC0 http://creativecommons.org/publicdomain/zero/1.0/ -->
<!-- ======================================================================= -->
<?xml-stylesheet type="text/css" href="../res/2.0/style/wowNeutral.css" ?>
<?xml-stylesheet type="text/css" href="album.css" ?>
<svg width="100%" height="100%" viewBox="0 0 800 550"
style="background:#181818"
xmlns="http://www.w3.org/2000/svg"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns:xlink="http://www.w3.org/1999/xlink"
onload="sw.photoAlbum.init();">
<title>Photo Album</title>
<desc>A framed photograph with a strip of thumbnails that slides up from the bottom edge. The strip scrolls with the pointer, a magnifier enlarges the thumbnails at its center, and clicking one shows it in the frame.</desc>
<rect width="100%" height="100%" fill="#181818" />
<svg width="800" height="550" x="0" y="0" viewBox="0 0 800 550"
xmlns="http://www.w3.org/2000/svg"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns:sw="http://www.svgopen.org/2004/svgWow"
xmlns:xlink="http://www.w3.org/1999/xlink"
overflow="visible">
<script xlink:href="../res/2.0/scripts/compat/no-unload.js" />
<script xlink:href="../res/2.0/scripts/yui/yahoo-dom-event/yahoo-dom-event.js" />
<script xlink:href="../res/2.0/scripts/yui/animation/animation-min.js" />
<script xlink:href="../res/2.0/scripts/dom-utils.js" />
<script xlink:href="compat.js" />
<script xlink:href="../res/2.0/scripts/tools/magnifier.js" />
<script xlink:href="../res/2.0/scripts/utils/ez-transform.js" />
<script xlink:href="../res/2.0/scripts/animation/animate.js" />
<script xlink:href="../res/2.0/scripts/widgets/sensor.js" />
<script xlink:href="../res/2.0/scripts/widgets/scroller.js" />
<script xlink:href="thumbnail.js" />
<script xlink:href="sources/photo-source.js" />
<script xlink:href="sources/local-photo-source.js" />
<script xlink:href="photo-container.js" />
<script xlink:href="framed-photo-container.js" />
<script xlink:href="album.js" />
<script xlink:href="album-app.js" />
<defs>
<filter id="dropShadow" x="-10%" y="-10%" width="120%" height="120%">
<feMorphology in="SourceAlpha" operator="dilate" radius="2" />
<feGaussianBlur stdDeviation="2" result="blur"/>
</filter>
<linearGradient id="thumbsOvercast" x1="0" y1="0" x2="1" y2="0">
<stop stop-color="black" stop-opacity="0.75" offset="0" />
<stop stop-color="black" stop-opacity="0" offset="0.05" />
<stop stop-color="black" stop-opacity="0" offset="0.95" />
<stop stop-color="black" stop-opacity="0.75" offset="1" />
</linearGradient>
<clipPath id="viewportClip">
<rect width="800" height="550" />
</clipPath>
</defs>
<g id="content" clip-path="url(#viewportClip)">
<rect id="background" x="0" y="0" rx="5" ry="5" width="800" height="550"/>
<g transform="translate(400,250)">
<image id="pictureContainer" xlink:href=""
x="-300" y="-175" width="600" height="350" />
<rect id="pictureFrame"
width="600" height="350" fill="none"
x="-300" y="-175" stroke="white" stroke-width="8" />
<g id="loadingPictureMessage" fill="white" opacity="0">
<rect x="-70" y="-25" width="140" height="70" fill="black"
fill-opacity="0.25" rx="5" ry="5" stroke="white"
stroke-opacity="0.25" stroke-width="2"/>
<g id="loadingGraphic">
<circle id="waitSpoke" cx="10" r="2" />
<use xlink:href="#waitSpoke" transform="rotate(30)" opacity="0.05"/>
<use xlink:href="#waitSpoke" transform="rotate(60)" opacity="0.1"/>
<use xlink:href="#waitSpoke" transform="rotate(90)" opacity="0.2"/>
<use xlink:href="#waitSpoke" transform="rotate(120)" opacity="0.3"/>
<use xlink:href="#waitSpoke" transform="rotate(150)" opacity="0.4"/>
<use xlink:href="#waitSpoke" transform="rotate(180)" opacity="0.5"/>
<use xlink:href="#waitSpoke" transform="rotate(210)" opacity="0.6"/>
<use xlink:href="#waitSpoke" transform="rotate(240)" opacity="0.7"/>
<use xlink:href="#waitSpoke" transform="rotate(270)" opacity="0.8"/>
<use xlink:href="#waitSpoke" transform="rotate(300)" opacity="0.9"/>
<use xlink:href="#waitSpoke" transform="rotate(330)" opacity="1"/>
</g>
<text font-family="Verdana" font-size="12" fill="white"
y="30"
text-anchor="middle">loading new image</text>
</g>
</g>
<g id="thumbnailsPane" transform="translate(0,420)">
<rect id="thumbnailsBounds"
pointer-events="none" shape-rendering="crispEdges"
stroke="none" stroke-opacity="0.5"
width="800" height="130" fill="none"/>
</g>
<rect id="thumbnailsPaneSensor" y="300" width="800" height="250"
fill="none" fill-opacity="0" stroke="none" />
</g>
<!-- Credit for the generated pictures -->
<text class="credits" x="790" y="20">original generated pictures</text>
</svg>
</svg>/photoAlbum/album.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
sw.photoAlbum = sw.photoAlbum || {};
yui = YAHOO;
/**
* Simple PhotoAlbum class.
*
* A <code>PhotoAlbum</code> manages a <code>PhotoSource</code>, displays
* the thumbnails in a scrolling pane and the current thumbnail selection
* in a main image display.
*
* @param p_photoSource the source of thumbnails and pictures.
* @param p_photoContainer responsible for displaying the selected picture.
* @param p_thumbnailsBounds the area where the thumbnails will be displayed
* in a scroller.
*/
sw.photoAlbum.Album = function (p_photoSource,
p_photoContainer,
p_thumbnailsBounds) {
this.initialize(p_photoSource, p_photoContainer, p_thumbnailsBounds);
};
/**
* @see constructor
*/
sw.photoAlbum.Album.prototype.initialize = function (p_photoSource,
p_photoContainer,
p_thumbnailsBounds) {
/**
* Picture cache
*/
var pictures = [];
/**
* Loaded thumbnails
*/
var thumbnails = [];
/**
* The photo source provides a common way to retrieve pages of photos
* and 'flip' through the image data.
*/
var photoSource = p_photoSource;
/**
* The container where the pictures are inserted for display.
*/
var photoContainer = p_photoContainer;
/**
* The bounds of this elements are used to build up the thumbnails view.
*/
var thumbnailsBounds = sw.stringToElement(p_thumbnailsBounds);
/**
* The bounding box of the thumbnail bounds area.
*/
var thumbnailsBoundsBBox = thumbnailsBounds.getBBox();
/**
* The group into which thumbnails are inserted.
*/
var thumbnailsContent;
/**
* Scroller for navigating thumbnails.
*/
var scroller;
/**
* The magnifier tool used to zoom into thumbnails.
*/
var magnifier;
/**
* The magnifier radius. Since we use normalized values, the
* magnifier radius depends on the content's width and the
* scroller bounds. The magnifierRadius is a ratio in the [0, 1]
* range of the scroller bounds. Since the magnifier works in the
* scrolled content's normalized space (i.e., where [0, 1] maps
* to [minContent.x, maxContent.y]), we recompute the magnifier's
* range every time the contentBox changes.
*/
var magnifierRadius = 0.3;
/**
* Current page index
*/
var pageIndex = -1;
/**
* Current page length
*/
var pageSize = -1;
/**
* Current picture index.
*/
var pictureIndex = -1;
/**
* Current picture lazy load index
*/
var lazyLoadPictureIndex = -1;
/**
* Image shown when an error occurs.
*/
var loadErrorImage = new Image();
loadErrorImage.src = "load-error-image.png";
/**
* Build the album components.
*/
function buildAlbum () {
// Create a container for the thumbnails content.
var scrollerContainer = thumbnailsBounds.parentNode.loadContent({
tag: "g"
});
thumbnailsContent = scrollerContainer.loadContent({tag: "g"});
// Keep track of the current thumbnail location
thumbnailsContent.curX = 0;
// Create a sensor from the thumbnails bounds
var thumbnailsSensor = new sw.widgets.Sensor(thumbnailsBounds, {
x: function (x) {
// Squaring the x axis speed with damper the speed
// when hovering about the scroller's center.
return x * Math.abs(x);
}
});
// Create a magnifier to zoom in the center thumbnails.
magnifier = new sw.tools.Magnifier(magnifierRadius, 0.5, 0, 1, 0.5);
// Create the thumbnails scroller
scroller = new sw.widgets.Scroller(scrollerContainer,
thumbnailsContent,
thumbnailsBounds,
{
damper: {
x: 0.2,
y: 0
},
sensor: thumbnailsSensor,
disableScroll: {
y: true
}
});
// Bind the magnifier's position to the scroll amount so that the
// magnifier always stays in the middle of the scroll area.
scroller.events.onScrollUpdate.subscribe(onScrollUpdate);
// Bind the sensor's control point to the mouse movement
document.addEventListener("pointermove", function (evt) {
thumbnailsSensor.setControlPoint({
x: evt.clientX,
y: evt.clientY
});
}, false);
thumbnailsContent.addEventListener("click", thumbSelected, false);
// Subscribe to the events generated by the photoSource
photoSource.events.pageCountRetrieved.subscribe(onPageCountRetrieved);
photoSource.events.pageRetrieved.subscribe(onPageRetrieved);
// Request retrieval of the first page to get started.
photoSource.retrievePageCount();
}
this.buildAlbum = buildAlbum;
/**
* Called when the photoShource has computed its page count.
* We simply retrieve the first page.
*/
function onPageCountRetrieved (type, args) {
if (args[0].count >= 1) {
photoSource.retrievePage(0);
} else {
alert("There are no pictures in the photo source");
}
}
/**
* Called when the photoSource has retrieved the list of pictures for a
* given page.
*/
function onPageRetrieved (type, args) {
var result = args[0];
var thumbnail;
var url;
if (result.size >= 1) {
pageIndex = result.index;
pageSize = result.size;
pictureIndex = -1;
lazyLoadPictureIndex = 0;
// Empty the current thumbnailsContent children.
thumbnailsContent.removeAllChildren();
thumbnailsContent.curX = 0;
thumbnails = [];
pictures = [];
// Get the new thumbnails and first picture.
for (var i = 0; i < result.size; i++) {
url = photoSource.getThumbnailURL(result.index, i);
thumbnail = new sw.photoAlbum.Thumbnail(url);
thumbnail.photoIndex = i;
thumbnail.events.onReady.subscribe(onThumbnailReady);
thumbnail.initThumbnail();
}
showPicture(pageIndex, 0);
// lazyLoadNextPicture();
} else {
alert("There are no pictures in page " + result.index);
}
}
/**
* Handles a new thumbnail when it becomes ready
*/
function onThumbnailReady (type, args) {
var evt = args[0];
var thumbnail = evt.thumbnail;
var p = Math.random();
var rotation = (thumbnail.MAX_THUMB_ROTATION -
thumbnail.MIN_THUMB_ROTATION) * (2 * p - 1);
if (rotation < 0) {
rotation -= thumbnail.MIN_THUMB_ROTATION;
} else {
rotation += thumbnail.MIN_THUMB_ROTATION;
}
thumbnailsContent.appendChild(thumbnail.element);
thumbnail.anchor();
// We shift by width / 4 because we apply a scale of 0.5
// and we translate by half the image's width
thumbnail.moveTo(thumbnailsContent.curX + evt.width / 4, 0);
thumbnail.rotate(rotation);
thumbnail.scale(0.5);
thumbnail.originalRotation = rotation;
thumbnail.originalX = thumbnail.x;
thumbnail.originalY = thumbnail.y;
thumbnailsContent.curX += evt.width * 0.5;
thumbnails.push(thumbnail);
scroller.updateContentBox();
}
/**
* Called back when the thumbnails scroller updates its scrolling area.
* As a result, we move the magnifier's position to match the center of
* the scroll area and we apply it to all the thumbnails.
*
* @param p_type the event type (not used here)
* @param p_args the arguments passed to the fire() call.
*/
function onScrollUpdate (p_type, p_args) {
var scroll = p_args[0];
// Compute the current magnifier radius, based on the
// current content width.
magnifier.setRadius(magnifierRadius *
thumbnailsBoundsBBox.width /
scroller.contentBox.width);
magnifier.setPosition(1 - scroll.x, 1 - scroll.y);
var t;
var pos = {};
var result = {};
var nt = thumbnails.length;
var bbox = scroller.contentBox;
for (var i = 0; i < nt; i++) {
t = thumbnails[i];
// Compute normalized position in the content's bounding
// box space.'
pos.x = (t.originalX - bbox.x) / bbox.width;
pos.y = (t.originalY - bbox.y) / bbox.height;
// Process normalized position
magnifier.processPoint(pos.x, pos.y, result);
// Apply displacement, rotation and scale to element.
t.rotate(result.p * t.originalRotation);
t.scale(result.magnification);
t.moveTo(bbox.x + result.x * bbox.width,
bbox.y + result.y * bbox.height);
}
}
/**
* Handles thumbnail selection
*
* @param p_evt the DOM event
*/
function thumbSelected (p_evt) {
var thumbnail = p_evt.target.thumbnail;
if (thumbnail !== undefined) {
showPicture(pageIndex, thumbnail.photoIndex);
}
}
/**
* Request showing the given picture
*
*/
function showPicture (p_pageIndex, p_photoIndex) {
pictureIndex = p_photoIndex;
var url = photoSource.getPictureURL(p_pageIndex, p_photoIndex);
var curPageIndex = p_pageIndex;
var image = undefined;
var loadHandler = function (evt) {
image.loaded = true;
image.error = false;
photoContainer.setImage(image);
if (pageIndex === curPageIndex) {
// lazyLoadNextPicture();
}
};
var errorHandler = function (evt) {
image.loaded = true;
photoContainer.setImage(loadErrorImage);
pictures[url] = loadErrorImage;
};
if (pictures[url] !== undefined) {
if (pictures[url].loaded === true) {
photoContainer.setImage(pictures[url]);
} else {
pictures[url].onload = loadHandler;
pictures[url].onerror = errorHandler;
pictures[url].onabort = errorHandler;
}
} else {
var image = new Image ();
pictures[url] = image;
image.onload = loadHandler;
image.onerror = errorHandler;
image.onabort = errorHandler;
photoContainer.showLoading();
image.src = url;
}
}
/**
* Shows the picture p_delta places after the current one, wrapping around.
*/
this.showRelative = function (p_delta) {
if (pageSize > 0) {
showPicture(pageIndex,
(pictureIndex + p_delta + pageSize) % pageSize);
}
};
/**
* The index of the picture on display.
*/
this.getPictureIndex = function () {
return pictureIndex;
};
/**
* Try to load next picture in the index.
*/
function lazyLoadNextPicture () {
var url = photoSource.getPictureURL(pageIndex, lazyLoadPictureIndex);
var curPageIndex = pageIndex;
var llpi = lazyLoadPictureIndex;
if (pictures[url] !== undefined) {
lazyLoadPictureIndex++;
if (lazyLoadPictureIndex < pageSize - 1) {
lazyLoadNextPicture()
}
} else {
var image = new Image();
pictures[url] = image;
image.loaded = false;
image.src = url;
image.onload = function (evt) {
image.loaded = true;
lazyLoadPictureIndex++;
if (pageIndex === curPageIndex) {
setTimeout(500, lazyLoadNextPicture());
}
}
}
}
};/photoAlbum/album-app.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
/**
* The app script puts the pieces together and assembles the different
* objects, such as the album and its source.
*/
sw.photoAlbum = sw.photoAlbum || {};
yui = YAHOO;
sw.photoAlbum.init = function () {
// Boiler plate demo initialization
sw.init();
var photoSource = new sw.photoAlbum.LocalPhotoSource();
var pictureContainer = new sw.photoAlbum.FramedPhotoContainer(
"pictureContainer",
"loadingPictureMessage",
"loadingGraphic",
"pictureFrame"
);
var album = new sw.photoAlbum.Album(photoSource,
pictureContainer,
"thumbnailsBounds");
album.buildAlbum();
// Create a sensor to show/hide the thumbnailsPane
var thumbnailsBounds = sw.stringToElement("thumbnailsBounds");
var thumbnailsPaneSensor =
new sw.widgets.Sensor("thumbnailsPaneSensor");
// Animations used to show and hide the thumbnail pane
var thumbnailsPane = thumbnailsBounds.parentNode;
thumbnailsPane.setAttribute("transform", "");
var thumbnailsPaneViewportBBox = thumbnailsPane.getViewportBBox();
var viewportHeight =
document.getElementById("background").getBBox().height;
var minTy = viewportHeight - thumbnailsPaneViewportBBox.height;
var maxTy = viewportHeight;
thumbnailsPane.setAttribute("transform", "translate(0," + maxTy + ")");
thumbnailsPane.ty = maxTy;
var showThumbnailsAnim =
new sw.animation.Animate("thumbnailsPane", {
txf: {
to: {ty: minTy},
template: "translate(0,#ty)"
},/*
ty: {
to: minTy
}*/
},
0.3, yui.util.Easing.easeOut, "translate(0,#ty)");
var hideThumbnailsAnim =
new sw.animation.Animate(thumbnailsPane, {
txf: {
to: {ty: maxTy},
template: "translate(0,#ty)"
},/*
ty: {
to: maxTy
}*/
},
0.3, yui.util.Easing.easeOut);
thumbnailsPaneSensor.events.onEnter.subscribe(function () {
hideThumbnailsAnim.stop();
showThumbnailsAnim.animate();
});
thumbnailsPaneSensor.events.onLeave.subscribe(function () {
showThumbnailsAnim.stop();
hideThumbnailsAnim.animate();
});
// Bind sensor to events. Pointer events also cover touch input.
function updatePaneSensor (evt) {
thumbnailsPaneSensor.setControlPoint({
x: evt.clientX,
y: evt.clientY
});
}
document.addEventListener("pointermove", updatePaneSensor, false);
document.addEventListener("pointerdown", updatePaneSensor, false);
// Keyboard: arrows change picture, T shows or hides the thumbnails.
var paneShown = false;
thumbnailsPaneSensor.events.onEnter.subscribe(function () { paneShown = true; });
thumbnailsPaneSensor.events.onLeave.subscribe(function () { paneShown = false; });
document.addEventListener("keydown", function (evt) {
if (evt.key === "ArrowRight") {
album.showRelative(1);
} else if (evt.key === "ArrowLeft") {
album.showRelative(-1);
} else if (evt.key === "t" || evt.key === "T") {
paneShown = !paneShown;
(paneShown ? hideThumbnailsAnim : showThumbnailsAnim).stop();
(paneShown ? showThumbnailsAnim : hideThumbnailsAnim).animate();
} else {
return;
}
evt.preventDefault();
}, false);
}/photoAlbum/album.css
#background {
fill: #303030;
}
#content {
font-family: Didot, Georgia, serif;
text-align:center;
}
.thumbnailFrame {
fill: none;
stroke: white;
stroke-width: 3;
}
.thumbnailsPaneBorder {
stroke: white;
shape-rendering: crispEdges;
}
.thumbnailShadow {
/* filter: url(album.svg#dropShadow);*/
}
#pictureShadow {
/* filter: url(album.svg#dropShadow);*/
}
#content {
touch-action: none;
}
.thumbnailFrame, .thumbnailShadow {
cursor: pointer;
}
.credits {
fill: white;
fill-opacity: 0.6;
font-family: 'Myriad Pro', 'Helvetica Neue', Arial, sans-serif;
font-size: 10px;
text-anchor: end;
}/photoAlbum/photo-container.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
sw.photoAlbum = sw.photoAlbum || {};
yui = YAHOO;
/**
* Base class responsible for displaying a picture. This provides a way for
*/
sw.photoAlbum.PhotoContainer = function () {
var events = {
onImageUpdate : new yui.util.CustomEvent(this.IMAGE_UPDATE),
onLoading : new yui.util.CustomEvent(this.LOADING)
};
this.events = events;
function setImage(img) {
events.onImageUpdate.fire(img);
}
this.setImage = setImage;
function showLoading () {
events.onLoading.fire();
}
this.showLoading = showLoading;
}
sw.photoAlbum.PhotoContainer.prototype.IMAGE_UPDATE = "IMAGE_UPDATE";
sw.photoAlbum.PhotoContainer.prototype.LOADING = "LOADING";
/photoAlbum/framed-photo-container.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
sw.photoAlbum = sw.photoAlbum || {};
yui = YAHOO;
/**
* Simple photo container which uses an image element and a rect element to
* display a picture. The initial size on the p_image element constrains the
* size of all images displayed in this container.
*
* @param p_image the image into which the image should be displayed
* @param p_loadingPictureMessage the id or element showing a 'loading picture'
* message. The element will be faded in when loading a picture and out
* when a new picture is set.
* @param p_loadingGraphic the id or element showing loading is under way.
* this graphic should be centered about the origin as it will be rotated
* about it's center while loading a picture.
* @param p_oFrame the rectangle frame
*/
sw.photoAlbum.FramedPhotoContainer = function (p_image,
p_loadingPictureMessage,
p_loadingGraphic,
p_oFrame) {
sw.photoAlbum.FramedPhotoContainer.superclass.constructor.call(this);
var image = sw.stringToElement(p_image);
var loadingPictureMessage = sw.stringToElement(p_loadingPictureMessage);
var loadingGraphic = sw.stringToElement(p_loadingGraphic);
var frame = null;
if (p_oFrame !== undefined) {
frame = sw.stringToElement(p_oFrame);
}
this.events.onImageUpdate.subscribe(onImageUpdate);
var attributes = image.getAttributes("width", "height");
var maxWidth = parseFloat(attributes.width);
var maxHeight = parseFloat(attributes.height);
var showLoadingPicture =
new sw.animation.Animate(loadingPictureMessage, {
opacity: {
to: 1
}
},
0.25);
var hideLoadingPicture =
new sw.animation.Animate(loadingPictureMessage, {
opacity: {
to: 0
}
},
0.25);
var animateLoadingPicture =
new sw.animation.Animate(loadingGraphic, {
txf: {
from: {r: 0},
to: {r: 360},
template: "rotate(#r)"
}
},
2, undefined, "rotate(#r)");
// Start animating the loading graphic when we start showing the loading
// animation.
showLoadingPicture.onBegin(function () {
animateLoadingPicture.animate();
});
animateLoadingPicture.onEnd(animateLoadingPicture);
// Start the showLoadingPicture animation when loading.
this.events.onLoading.subscribe(function () {
showLoadingPicture.animate();
});
function onImageUpdate (type, args) {
var img = args[0];
var scale = 1;
if (img.width > maxWidth) {
scale = maxWidth / img.width;
}
if (img.height * scale > maxHeight) {
scale = maxHeight / img.height;
}
image.setAttributes({
"xlink:href": img.src,
width: scale * img.width,
height: scale * img.height,
x: -scale * img.width / 2,
y: -scale * img.height / 2
});
if (frame !== null) {
frame.setAttributes({
width: scale * img.width,
height: scale * img.height,
x: -scale * img.width / 2,
y: -scale * img.height / 2
});
}
showLoadingPicture.stop();
hideLoadingPicture.animate();
}
}
yui.lang.extend(sw.photoAlbum.FramedPhotoContainer,
sw.photoAlbum.PhotoContainer,
{});/res/2.0/scripts/widgets/scroller.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
sw.widgets = sw.widgets || {};
yui = YAHOO;
/**
* A <code>Scroller</code> scrolls content at the desired 'speed' along the
* x and/or y axis. It dampers it's speeds when getting closer to the edges
* of the scroll area.
*
* @param p_container the element into which the scroller will create its
* content. Can be a <code>String</code> or an <code>Element</code>.
*
* @param p_content element to scroll in the container. Can be either a
* <code>String</code> or an <code>Element</code>
*
* @param p_scrollBounds the limits of the scroll area.
*
* @param p_oConfig Optional. The configuration parameters for the scroller:
* {
* damper: {
* x: Number in the [0, 1] range
* y: Number in the [0, 1] range
* },
* sensor: Object with an onIntensityUpdate event.
* scrollUnit: {
* x: Number,
* y: Number
* },
* disableScroll: {
* x: Boolean,
* y: Boolean
* },
* initialScroll: {
* x: Number (in the [0, 1] range)
* y: Number (in the [0, 1] range)
* },
* maxAccelleration: {
* x: Number (in the [0, 1] range)
* y: Number (in the [0, 1] range)
* }
*/
sw.widgets.Scroller = function (p_container, p_content,
p_scrollBounds, p_oConfig) {
this.initialize(p_container, p_content, p_scrollBounds, p_oConfig);
};
sw.widgets.Scroller.prototype = {
/*
* @see constructor documentation
*/
initialize : function (p_container, p_content, p_scrollBounds, p_oConfig) {
/**
* The parent container.
*/
var container;
/**
* The scrolled content
*/
var content;
/**
* The bounds of the scrolling area.
*/
var scrollBounds;
/**
* The id for the scroller's setInterval. Undefined when not running
*/
var scrollingRunningId = undefined;
/**
* The currently set scrolling speed along each axis.
*/
var scrollSpeed = {
x: 0,
y: 0
};
/**
* The actual scroll speed along each axis. May be different from the
* requested scroll speed, for example when reaching the end of the
* scroll area or while dampering the speed.
*/
var actualScrollSpeed = {
x: 0,
y: 0
};
/**
* The last computed scroll speed.
*/
var previousScrollSpeed = {
x: 0,
y: 0
};
/**
* The scroller's configuration defaults
*/
var config = {
/**
* The scroller's damper
*
*/
damper: {
x: 0.1,
y: 0.1
},
/**
* The amount of scroll, at full speed, along each axis, for
* each frame.
*/
scrollUnit: {
x: 40,
y: 40
},
/**
* Optional. If specified, listen to this speed controller to
* set the scrolling speed.
*/
sensor: undefined,
/**
* Controls if scroll is disabled along one or both of the axis
*
*/
disableScroll: {
x: false,
y: false
},
/**
* Initial scroll position.
*/
initialScroll: {
x: 0.5,
y: 0.5
},
/**
* Maximum acceleration
*/
maxAcceleration: {
x: 0.01,
y: 0.01
}
};
/**
* Current scrolling amount. We keep the currentScroll normalized to
* the [0, 1] range, where 0 is the minimal scroll and 1 the maximum.
*/
var curScroll = {
x: 0,
y: 0
};
/**
* Current acceleration. May be undefined
*/
var acceleration = {
x: undefined,
y: undefined,
targetSpeed: {
x: 0,
y: 0
}
};
/**
* Compute the conent bounds now. They can be updated with an
* updateContentBounds call. The content bounds are not recomputed
* on each scroll to avoid counter effects, for example when
* magnifying the center of the content on scroll, which changes the
* content bounds and sets off the scrolling algorithm.
*/
var contentBox;
// =====================================================================
// Apply config parameters
if (p_oConfig !== undefined && p_oConfig !== null) {
if (typeof p_oConfig.damper === "object") {
if (typeof p_oConfig.damper.x === "number") {
config.damper.x = p_oConfig.damper.x;
}
if (typeof p_oConfig.damper.y === "number") {
config.damper.y = p_oConfig.damper.y;
}
}
if (typeof p_oConfig.sensor === "object" &&
typeof p_oConfig.sensor.events === "object" &&
p_oConfig.sensor.events.onIntensityUpdate !== undefined) {
config.sensor = p_oConfig.sensor;
}
if (typeof p_oConfig.scrollUnit === "object") {
if (typeof p_oConfig.scrollUnit.x === "number") {
config.scrollUnit.x = p_oConfig.scrollUnit.x;
}
if (typeof p_oConfig.scrollUnit.y === "number") {
config.scrollUnit.y = p_oConfig.scrollUnit.y;
}
}
if (typeof p_oConfig.disableScroll === "object") {
if (typeof p_oConfig.disableScroll.x === "boolean") {
config.disableScroll.x = p_oConfig.disableScroll.x;
}
if (typeof p_oConfig.disableScroll.y === "boolean") {
config.disableScroll.y = p_oConfig.disableScroll.y;
}
}
if (typeof p_oConfig.initialScroll === "object") {
if (typeof p_oConfig.initialScroll.x === "number") {
config.initialScroll.x = p_oConfig.initialScroll.x;
}
if (typeof p_oConfig.initialScroll.y === "number") {
config.initialScroll.y = p_oConfig.initialScroll.y;
}
}
if (typeof p_oConfig.maxAcceleration === "object") {
if (typeof p_oConfig.maxAcceleration.x === "number") {
config.maxAcceleration.x = p_oConfig.maxAcceleration.x;
}
if (typeof p_oConfig.maxAcceleration.y === "number") {
config.maxAccelleration.y = p_oConfig.maxAcceleration.y;
}
}
}
// If the speed controller is defined, listen to its update.
if (config.sensor !== undefined) {
config.sensor.events.onIntensityUpdate.subscribe(
function (type, args) {
// Invert the sensor's intensity. If to the right
// of the sensor's center, move left (i.e., negative speed).
// Likewise on the y-azis.
var xSpeed = -args[0].x;
var ySpeed = -args[0].y;
updateScrollSpeed(xSpeed, ySpeed);
}
);
config.sensor.events.onLeave.subscribe(
function () {
setAcceleration(config.maxAcceleration.x,
config.maxAcceleration.y,
{x: 0, y: 0});
}
);
}
// Convert from id to element if need be
container = sw.stringToElement(p_container);
content = new sw.utils.EZTransform(p_content);
scrollBounds = sw.stringToElement(p_scrollBounds);
container.appendChild(content.element);
// Make the container group as this widget's 'element'.
this.element = content.element;
// Initialize events.
var events = {
onScrollUpdate : new YAHOO.util.CustomEvent(this.SCROLL_UPDATE)
};
this.events = events;
// Set the initial scroll
curScroll.x = config.initialScroll.x;
curScroll.y = config.initialScroll.y;
updateContentBox();
updateScroll();
/**
* Starts or stop scrolling, depending on whether or not there is
* a non-zero speed.
*/
function checkScrollState () {
var running = (actualScrollSpeed.x != 0 ||
actualScrollSpeed.y != 0);
if (running === true) {
if (scrollingRunningId === undefined) {
scrollingRunningId =
setInterval(updateScroll, 40);
}
} else {
if (scrollingRunningId !== undefined) {
clearInterval(scrollingRunningId);
scrollingRunningId = undefined;
}
}
}
/**
* Updates the scrolling speed along the x and y axis.
*
* @param p_xSpeed the speed along the x-axis
* @param p_ySpeed the speed along the y-axis
*/
function updateScrollSpeed(p_xSpeed, p_ySpeed) {
if (config.disableScroll.x === false) {
scrollSpeed.x = p_xSpeed;
}
if (config.disableScroll.y === false) {
scrollSpeed.y = p_ySpeed;
}
actualScrollSpeed.x = scrollSpeed.x;
actualScrollSpeed.y = scrollSpeed.y;
// Stop accelerations if any.
acceleration.x = undefined;
acceleration.y = undefined;
computeActualSpeed();
checkScrollState();
}
/**
* Sets the acceleration along each axis.
*
* @param p_xAccel the acceleration along the x-axis
* @param p_yAccel the acceleration along the y-axis
* @param p_targetSpeed the target speed
*/
function setAcceleration (p_xAccel, p_yAccel, p_targetSpeed) {
acceleration = {
x: p_xAccel,
y: p_yAccel,
targetSpeed: {
x: p_targetSpeed.x,
y: p_targetSpeed.y
}
};
computeActualSpeed();
checkScrollState();
}
/**
* Computes the actual speed, accounting for constraints and dampering,
* for example.
*/
function computeActualSpeed () {
computeActualAxisSpeed("x");
computeActualAxisSpeed("y");
}
/**
* Implementation helper. The scroll happens in the
*
* [-contentBox.width + scrollBox.width / 2, scrollBox.width / 2] and
* [-contentBox.height + scrollBox.height / 2, scrollBox.height / 2]
*
* ranges on each axis.
*/
function computeActualAxisSpeed (xOrY) {
var scrollLeft;
var damper = 1;
// Check if we have reached the end of the scrolling area
// or if we are in the damper zone
if (scrollSpeed[xOrY] < 0) {
// Moving back to zero
scrollLeft = curScroll[xOrY];
} else {
scrollLeft = 1 - curScroll[xOrY];
}
if (scrollLeft < config.damper[xOrY]) {
damper = scrollLeft / config.damper[xOrY];
}
// If there is an acceleration, apply it now if need be
if (acceleration[xOrY] !== undefined &&
config.disableScroll[xOrY] === false) {
// There is an acceleration defined.
// We need to move the actual speed towards the target speed.
if (previousScrollSpeed[xOrY] > acceleration.targetSpeed[xOrY]){
actualScrollSpeed[xOrY] = previousScrollSpeed[xOrY] -
acceleration[xOrY];
if (actualScrollSpeed[xOrY] <
acceleration.targetSpeed[xOrY]) {
actualScrollSpeed[xOrY] =
acceleration.targetSpeed[xOrY];
}
} else {
actualScrollSpeed[xOrY] = previousScrollSpeed[xOrY] +
acceleration[xOrY];
if (actualScrollSpeed[xOrY] >
acceleration.targetSpeed[xOrY]) {
actualScrollSpeed[xOrY]=
acceleration.targetSpeed[xOrY];
}
}
// If we have reached the target speed, stop the acceleration
if (actualScrollSpeed[xOrY] === acceleration.targetSpeed[xOrY]) {
acceleration[xOrY] = undefined;
scrollSpeed[xOrY] = acceleration.targetSpeed[xOrY];
}
actualScrollSpeed[xOrY] *= damper;
} else {
actualScrollSpeed[xOrY] =
scrollSpeed[xOrY] * damper;
}
}
/**
* Take the current content bounding box into account for scrolling
* computation purposes.
* @see the contentBox variable documentation for a discussion on why
* the contentBox is not dynamically taken into account.
*/
function updateContentBox () {
contentBox = content.element.getBBox();
this.contentBox = contentBox;
updateScroll();
}
this.updateContentBox = updateContentBox;
/**
* Handles scrolling. This is where the content is actually positioned.
*/
function updateScroll () {
if (contentBox !== null && contentBox.width > 0 &&
contentBox.height > 0) {
var scrollBy = {
x: 0,
y: 0
};
var scrollBox = scrollBounds.getBBox();
var scrollRange = {
x: contentBox.width,
y: contentBox.height
};
var minScroll = {
x: -contentBox.width + scrollBox.width / 2,
y: -contentBox.height + scrollBox.height / 2
};
var maxScroll = {
x: scrollBox.width / 2,
y: scrollBox.height / 2
};
var sx, sy;
// Account for dampering or other effects.
computeActualSpeed();
previousScrollSpeed.x = actualScrollSpeed.x;
previousScrollSpeed.y = actualScrollSpeed.y;
scrollBy.x = actualScrollSpeed.x * config.scrollUnit.x;
scrollBy.y = actualScrollSpeed.y * config.scrollUnit.y;
curScroll.x += scrollBy.x / scrollRange.x;
curScroll.y += scrollBy.y / scrollRange.y;
// Clip to allowed range
if (curScroll.x > 1) {
curScroll.x = 1;
} else if (curScroll.x < 0) {
curScroll.x = 0;
}
if (curScroll.y > 1) {
curScroll.y = 1;
} else if (curScroll.y < 0) {
curScroll.y = 0;
}
// Move the content to the origin, then to the scrollBox's
// origin and and then apply the scroll'
sx = -contentBox.x + scrollBox.x +
curScroll.x * maxScroll.x + (1 - curScroll.x) * minScroll.x;
sy = -contentBox.y + scrollBox.y +
curScroll.y * maxScroll.y + (1 - curScroll.y) * minScroll.y;
content.moveTo(sx, sy);
events.onScrollUpdate.fire({x: curScroll.x, y: curScroll.y});
// In case we have reached zero speed, stop the setInterval.
checkScrollState();
}
}
// Make updateScroll public.
this.updateScroll = updateScroll;
},
// Constants
SCROLL_UPDATE: "SCROLL_UPDATE"
};/res/2.0/scripts/widgets/sensor.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
sw.widgets = sw.widgets || {};
yui = YAHOO;
/**
* An <code>Sensor</code> which computes an intensity along the x and y axis
* based on the distance between its sensor element and a control point
* (typically followin the mouse mouvements). The intensity is at 1 in the
* center and zero on the edges.
*
* Example:
* <code>
* var sensor = new sw.widgets.Sensor(sensorElt);
*
* sensor.events.onIntensityUpdate.subscribe(function (type, args) {
* var x = args[0].x;
* var y = args[0].y
* });
* function onMouseMove (event) {
* sensor.setControlPoint({x: event.clientX, y: event.clientY});
* }
*
* </code>
*
* @param p_sensor an <code>Element</code> or element id. This element's
* bounds define the sensor area.
* @param p_oIntensityFunctions with x and y functions to interpolate the values
* in the [0, 1] range.
*/
sw.widgets.Sensor = function (p_sensor, p_oIntensityFunctions) {
this.initialize(p_sensor, p_oIntensityFunctions);
};
sw.widgets.Sensor.prototype = {
/**
* @param p_sensor an <code>Element</code> or element id. This element's
* bounds define the sensor area.
* @param p_oIntensityFunctions with x and y functions to interpolate the
* values in the [0, 1] range.
*/
initialize : function (p_sensor, p_oIntensityFunctions) {
var sensor = sw.stringToElement(p_sensor);
this.element = sensor;
var curIntensity = {
x: 0,
y: 0,
out: {
x: true,
y: true
},
isOut: true
};
var previousIntensity = {
x: 0,
y: 0,
isOut: true
};
var speedFunctions = {
x: function (x) { return x; },
y: function (y) { return y; }
};
if (p_oIntensityFunctions !== undefined &&
p_oIntensityFunctions !== null) {
if (typeof p_oIntensityFunctions.x === "function") {
speedFunctions.x = p_oIntensityFunctions.x;
}
if (typeof p_oIntensityFunctions.y === "function") {
speedFunctions.y = p_oIntensityFunctions.y;
}
}
this.events = {};
this.events.onIntensityUpdate =
new YAHOO.util.CustomEvent(this.INTENSITY_UPDATE);
this.events.onEnter =
new YAHOO.util.CustomEvent(this.ENTER);
this.events.onLeave =
new YAHOO.util.CustomEvent(this.LEAVE);
/**
* Computes the intensity along an axis.
*
* @param xOrY the axis name
* @param ref the reference point
* @param ctrl the control point
* @param hLength the sensor half length along the axis
*/
function computeAxisIntensity (xOrY, ref, ctrl, hLength) {
var i = (ctrl - ref) / hLength;
if (i > 1) {
i = 1;
curIntensity.out[xOrY] = true;
} else if (i < -1) {
i = -1;
curIntensity.out[xOrY] = true;
} else {
curIntensity.out[xOrY] = false;
}
curIntensity[xOrY] = i;
}
/**
* Computes the current speed. The speed is normalized to the [0, 1]
* interval.
*
* @param p_ctrl the control points to measure distance against the
* reference point.
*/
this.setControlPoint = function (p_ctrl) {
var ictm = sensor.getScreenCTM().inverse();
var bounds = sensor.getBBox();
// ref is in the coordinate systme of the sensor element
var ref = {
x: bounds.x + bounds.width / 2,
y: bounds.y + bounds.height /2
};
// ctrl is now in the same coordinate system as the sensor element
var ctrl = ictm.transformPoint(p_ctrl);
computeAxisIntensity("x", ref.x, ctrl.x, bounds.width / 2);
computeAxisIntensity("y", ref.y, ctrl.y, bounds.height / 2);
curIntensity.isOut = curIntensity.out.x || curIntensity.out.y;
curIntensity.x = speedFunctions.x(curIntensity.x, curIntensity.y);
curIntensity.y = speedFunctions.y(curIntensity.y, curIntensity.x);
if (curIntensity.isOut) {
// We are out. Generate a LEAVE event if we were not out
// before.
if (!previousIntensity.isOut) {
this.events.onLeave.fire();
}
} else {
if (previousIntensity.isOut) {
// We just re-entered the sensor
this.events.onEnter.fire();
}
this.events.onIntensityUpdate.fire(curIntensity);
}
previousIntensity.x = curIntensity.x;
previousIntensity.y = curIntensity.y;
previousIntensity.isOut = curIntensity.isOut;
};
},
// Constants
INTENSITY_UPDATE: "INTENSITY_UPDATE",
LEAVE: "LEAVE",
ENTER: "ENTER"
}
/photoAlbum/thumbnail.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
sw.photoAlbum = sw.photoAlbum || {};
yui = YAHOO;
/**
* This class is used to load and provide effects on thumbnails images.
*/
/**
* Constructor
*
* @param p_thumbURL the url for the thumbnail image
* @param p_oImageURL optional the url for the corresponding image
*/
sw.photoAlbum.Thumbnail = function (p_thumbURL, p_oImageURL) {
this.thumbURL = p_thumbURL;
this.imageURL = p_oImageURL;
this.events = {};
this.events.onReady = new YAHOO.util.CustomEvent(this.THUMBNAIL_READY);
sw.photoAlbum.Thumbnail.superclass.constructor.call(this, null);
};
yui.lang.extend(sw.photoAlbum.Thumbnail, sw.utils.EZTransform, {
// =============================================================================
// Constants
// =============================================================================
MAX_THUMB_ROTATION: 35,
MIN_THUMB_ROTATION: 10,
THUMBNAIL_READY: "THUMBNAIL_READY",
/**
* Initializes thumbnail by initiating the image download.
*/
initThumbnail : function () {
this.thumbImage = new Image();
this.scaleFactor = 1;
this.rotation = 0;
this.x = 0;
this.y = 0;
var that = this;
this.thumbImage.onload = function (evt) {
that.buildThumbContent();
that.events.onReady.fire({
thumbnail: that,
width: that.thumbImage.width,
height: that.thumbImage.height
});
}
// A picture that fails to load must not leave a page unfinished.
this.thumbImage.onerror = function () {
that.thumbImage.onerror = null;
that.thumbImage.src = "load-error-image.png";
};
this.thumbImage.src = this.thumbURL;
},
/**
* Builds the graphical content for this thumbnail
*/
buildThumbContent : function () {
var thumbImage = this.thumbImage;
var w = thumbImage.width;
var h = thumbImage.height;
var c;
var thumbnailInsert = sw.loadContent.call(null,
{
tag: "g",
children: [
{
tag: "rect",
"class": "thumbnailShadow",
width: thumbImage.width,
height: thumbImage.height
},
{
tag: "image",
"xlink:href": thumbImage.src,
width: thumbImage.width,
height: thumbImage.height,
id: "thumb_" + this.pictureName
},
{
tag: "rect",
width: thumbImage.width,
height: thumbImage.height,
"class": "thumbnailFrame"
}
]
}
);
// Add a 'thumbnail' reference to all the content elements, so that
// it can be used on events triggered by these elements.
thumbnailInsert.thumbnail = this;
c = thumbnailInsert.firstChild;
while (c !== null) {
c.thumbnail = this;
c = c.nextSibling;
}
this.setWrapped(thumbnailInsert);
}
});
/photoAlbum/compat.js
/**
* Small compatibility layer for the 2009 demo code, loaded after dom-utils.js.
* - getTransformToElement was removed from browsers.
* - SVGMatrix.transformPoint now returns a new point in some engines, so the
* viewport bounding box is computed here without relying on it.
* Released under CC0, like the demos that use it.
*/
(function () {
var proto = (window.SVGGraphicsElement || window.SVGElement).prototype;
if (!proto.getTransformToElement) {
proto.getTransformToElement = function (target) {
return target.getScreenCTM().inverse().multiply(this.getScreenCTM());
};
}
sw.getViewportBBox = function () {
var b = this.getBBox();
var viewport = this.nearestViewportElement || this.ownerSVGElement;
var m = viewport.getScreenCTM().inverse().multiply(this.getScreenCTM());
var xs = [], ys = [];
[[b.x, b.y], [b.x + b.width, b.y], [b.x, b.y + b.height],
[b.x + b.width, b.y + b.height]].forEach(function (p) {
xs.push(m.a * p[0] + m.c * p[1] + m.e);
ys.push(m.b * p[0] + m.d * p[1] + m.f);
});
var minX = Math.min.apply(null, xs), minY = Math.min.apply(null, ys);
return {
x: minX,
y: minY,
width: Math.max.apply(null, xs) - minX,
height: Math.max.apply(null, ys) - minY
};
};
})();
/photoAlbum/sources/photo-source.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
sw.photoAlbum = sw.photoAlbum || {};
yui = YAHOO;
/**
* Base class for photo sources. Implementations need to implement the
* appropriate "XYZImpl" methods.
*/
sw.photoAlbum.PhotoSource = function () {
this.events = {
pageCountRetrieved :
new yui.util.CustomEvent(this.PAGE_COUNT_RETRIEVED),
pageRetrieved :
new yui.util.CustomEvent(this.PAGE_RETRIEVED)
};
}
sw.photoAlbum.PhotoSource.prototype = {
/**
* Refer back to the constructor
*/
constructor: sw.photoAlbum.PhotoSource,
/**
* Request the retrieval of the page count.
*/
retrievePageCount : function () {
throw new Error("Should be implemented by concrete implementations");
},
/**
* Request the retrieval of the first page
*
* @param pageIndex the index of the page to retrieve.
*/
retrievePage : function (pageIndex) {
throw new Error("Should be implemented by concrete implementations");
},
/**
* Request the thumbnail url for the given page and index
*
* @param pageIndex
* @param photoIndex
*/
getThumbnailURL : function (pageIndex, photoIndex) {
throw new Error("Should be implemented by concrete implementations");
},
/**
* Request the image for the given page and index
*
* @param pageIndex
* @param photoIndex
*/
getPictureURL : function (pageIndex, photoIndex) {
throw new Error("Should be implemented by concrete implementations");
},
// Constants
PAGE_COUNT_RETRIEVED : "PAGE_COUNT_RETRIEVED",
PAGE_RETRIEVED : "PAGE_RETRIEVED"
};
/photoAlbum/sources/local-photo-source.js
/**
* Local photo source for the Photo Album and Light Table demos.
*
* It replaces the original remote source. All pictures are original and were
* computed by generate-photographs.js, so the demos make no remote requests.
* Released under CC0, like the demos that use it.
*/
sw.photoAlbum = sw.photoAlbum || {};
yui = YAHOO;
sw.photoAlbum.generatedPhotos = [{"name":"photo-01","title":"Ridges 1"},
{"name":"photo-02","title":"Open water 1"},
{"name":"photo-03","title":"River stones 1"},
{"name":"photo-04","title":"Fog in the pines 1"},
{"name":"photo-05","title":"Cloud bank 1"},
{"name":"photo-06","title":"Still lake 1"},
{"name":"photo-07","title":"Dunes 1"},
{"name":"photo-08","title":"Garden light 1"},
{"name":"photo-09","title":"Night sky 1"},
{"name":"photo-10","title":"Farmland 1"},
{"name":"photo-11","title":"Aurora 1"},
{"name":"photo-12","title":"Harbor city 1"},
{"name":"photo-13","title":"Ridges 2"},
{"name":"photo-14","title":"Open water 2"},
{"name":"photo-15","title":"River stones 2"},
{"name":"photo-16","title":"Fog in the pines 2"},
{"name":"photo-17","title":"Cloud bank 2"},
{"name":"photo-18","title":"Still lake 2"},
{"name":"photo-19","title":"Dunes 2"},
{"name":"photo-20","title":"Garden light 2"},
{"name":"photo-21","title":"Night sky 2"},
{"name":"photo-22","title":"Farmland 2"},
{"name":"photo-23","title":"Aurora 2"},
{"name":"photo-24","title":"Harbor city 2"},
{"name":"photo-25","title":"Ridges 3"},
{"name":"photo-26","title":"Open water 3"},
{"name":"photo-27","title":"River stones 3"},
{"name":"photo-28","title":"Fog in the pines 3"},
{"name":"photo-29","title":"Cloud bank 3"},
{"name":"photo-30","title":"Still lake 3"},
{"name":"photo-31","title":"Dunes 3"},
{"name":"photo-32","title":"Garden light 3"},
{"name":"photo-33","title":"Night sky 3"},
{"name":"photo-34","title":"Farmland 3"},
{"name":"photo-35","title":"Aurora 3"},
{"name":"photo-36","title":"Harbor city 3"},
{"name":"photo-37","title":"Ridges 4"},
{"name":"photo-38","title":"Open water 4"},
{"name":"photo-39","title":"River stones 4"},
{"name":"photo-40","title":"Fog in the pines 4"},
{"name":"photo-41","title":"Cloud bank 4"},
{"name":"photo-42","title":"Still lake 4"},
{"name":"photo-43","title":"Dunes 4"},
{"name":"photo-44","title":"Garden light 4"},
{"name":"photo-45","title":"Night sky 4"},
{"name":"photo-46","title":"Farmland 4"},
{"name":"photo-47","title":"Aurora 4"},
{"name":"photo-48","title":"Harbor city 4"}];
/**
* @param p_oConfig optional: { pageSize: Number }. Defaults to one page holding
* every picture.
*/
sw.photoAlbum.LocalPhotoSource = function (p_oConfig) {
sw.photoAlbum.LocalPhotoSource.superclass.constructor.call(this);
this.photos = sw.photoAlbum.generatedPhotos;
this.pageSize = (p_oConfig && p_oConfig.pageSize) || this.photos.length;
};
yui.lang.extend(sw.photoAlbum.LocalPhotoSource, sw.photoAlbum.PhotoSource, {
retrievePageCount : function () {
var that = this;
setTimeout(function () {
that.events.pageCountRetrieved.fire({
count: Math.ceil(that.photos.length / that.pageSize)
});
}, 0);
},
retrievePage : function (pageIndex) {
var start = pageIndex * this.pageSize;
var size = Math.min(this.pageSize, this.photos.length - start);
var that = this;
setTimeout(function () {
that.events.pageRetrieved.fire({index: pageIndex, size: size});
}, 0);
},
_photo : function (pageIndex, photoIndex) {
return this.photos[pageIndex * this.pageSize + photoIndex];
},
getThumbnailURL : function (pageIndex, photoIndex) {
return "pictures/thumbnails/thumb_" +
this._photo(pageIndex, photoIndex).name + ".jpg";
},
getPictureURL : function (pageIndex, photoIndex) {
return "pictures/" + this._photo(pageIndex, photoIndex).name + ".jpg";
},
getTitle : function (pageIndex, photoIndex) {
return this._photo(pageIndex, photoIndex).title;
}
});
/photoAlbum/sources/generate-photographs.js
/**
* Procedural "photographs" for the Photo Album and Light Table demos.
*
* Every picture in photoAlbum/pictures was computed by this file. No camera,
* stock image or third-party texture is involved. renderPhotograph(index, w, h)
* is deterministic: the same index and size always give the same pixels.
*
* The demos do not run this code. They load the JPEG files it produced.
* This source is released under CC0, like the demos that use it.
*/
(function (root) {
'use strict';
function prng(a) {
return function () {
a = (a + 0x6D2B79F5) | 0;
var t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function Noise(seed) {
var rnd = prng(seed);
var values = new Float32Array(256);
var perm = new Uint8Array(512);
var i, j, t;
for (i = 0; i < 256; i++) { values[i] = rnd(); perm[i] = i; }
for (i = 255; i > 0; i--) {
j = Math.floor(rnd() * (i + 1));
t = perm[i]; perm[i] = perm[j]; perm[j] = t;
}
for (i = 0; i < 256; i++) { perm[i + 256] = perm[i]; }
this.at = function (x, y) {
var xi = Math.floor(x), yi = Math.floor(y);
var fx = x - xi, fy = y - yi;
var u = fx * fx * (3 - 2 * fx), v = fy * fy * (3 - 2 * fy);
var X = xi & 255, Y = yi & 255;
var a = values[perm[X + perm[Y]]];
var b = values[perm[X + 1 + perm[Y]]];
var c = values[perm[X + perm[(Y + 1) & 255]]];
var d = values[perm[X + 1 + perm[(Y + 1) & 255]]];
return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
};
}
Noise.prototype.fbm = function (x, y, octaves) {
var sum = 0, amp = 0.5, norm = 0;
for (var i = 0; i < octaves; i++) {
sum += amp * this.at(x, y);
norm += amp;
amp *= 0.5;
x = x * 2.03 + 17.1;
y = y * 2.03 + 9.2;
}
return sum / norm;
};
Noise.prototype.ridged = function (x, y, octaves) {
var sum = 0, amp = 0.5, norm = 0, n;
for (var i = 0; i < octaves; i++) {
n = 1 - Math.abs(2 * this.at(x, y) - 1);
sum += amp * n * n;
norm += amp;
amp *= 0.5;
x = x * 2.1 + 3.7;
y = y * 2.1 + 5.3;
}
return sum / norm;
};
function clamp(x, a, b) { return x < a ? a : (x > b ? b : x); }
function smooth(a, b, x) { var t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); }
function mix(a, b, t) { return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; }
function scale(c, k) { return [c[0] * k, c[1] * k, c[2] * k]; }
function add(a, b, k) { return [a[0] + b[0] * k, a[1] + b[1] * k, a[2] + b[2] * k]; }
// Times of day: zenith, horizon, sun, haze
var SKIES = [
{ top: [38, 74, 130], low: [246, 186, 130], sun: [255, 226, 170], haze: [226, 170, 150] },
{ top: [44, 110, 186], low: [196, 224, 240], sun: [255, 250, 232], haze: [176, 204, 222] },
{ top: [52, 44, 104], low: [250, 128, 76], sun: [255, 208, 120], haze: [214, 118, 104] },
{ top: [16, 26, 62], low: [132, 106, 150], sun: [244, 196, 186], haze: [92, 88, 130] }
];
function skyColor(n, s, u, v, sunU, sunV, aspect, cloudy) {
var c = mix(s.top, s.low, Math.pow(clamp(v, 0, 1), 1.5));
var dx = (u - sunU) * aspect, dy = v - sunV;
var d = Math.sqrt(dx * dx + dy * dy);
c = add(c, s.sun, 0.55 * Math.exp(-d * 4.5));
c = mix(c, s.sun, smooth(0.052, 0.04, d));
if (cloudy > 0) {
var cl = n.fbm(u * 3.2 * aspect + 4, v * 9 + 2, 6);
var k = smooth(0.56 - cloudy * 0.12, 0.76, cl) * (1 - smooth(0.7, 1, v));
var lit = mix(scale(s.low, 0.72), s.sun, clamp(1 - d * 1.5, 0, 1));
c = mix(c, lit, k * 0.86);
}
return c;
}
function ridgeLine(n, w, base, amp, freq, off) {
var a = new Float32Array(w);
for (var x = 0; x < w; x++) {
a[x] = base - amp * (n.ridged(x / w * freq + off, off * 1.7, 6) - 0.32);
}
return a;
}
/* ===== Scenes. Each returns shade(px, py, u, v) giving [r, g, b]. ===== */
function mountains(w, h, r, n) {
var s = SKIES[Math.floor(r() * 4)], aspect = w / h;
var sunU = 0.2 + r() * 0.6, sunV = 0.3 + r() * 0.22;
var L = 5, ridges = [], tint = [58 + r() * 26, 62 + r() * 22, 74 + r() * 26], i;
for (i = 0; i < L; i++) {
ridges.push(ridgeLine(n, w, 0.45 + i * 0.105, 0.34 - i * 0.03, (1.6 + i * 0.9) * aspect, r() * 90 + i * 11));
}
return function (px, py, u, v) {
for (var l = L - 1; l >= 0; l--) {
if (v >= ridges[l][px]) {
var depth = l / (L - 1);
var below = v - ridges[l][px];
var tex = n.fbm(u * (9 + l * 5) * aspect + l * 7, v * (20 + l * 7), 5);
var c = scale(tint, 0.5 + tex * 0.95);
if (l <= 2 && below < 0.05 + tex * 0.09) {
c = mix(c, [236, 236, 240], smooth(0.05 + tex * 0.09, 0.012, below) * 0.92);
}
if (l === L - 1) { c = mix(c, [34, 52, 38], 0.72); }
return mix(c, s.haze, Math.pow(1 - depth, 1.5) * 0.78);
}
}
return skyColor(n, s, u, v, sunU, sunV, aspect, 0.6);
};
}
function lake(w, h, r, n) {
var inner = mountains(w, h, r, n);
var line = 0.56 + r() * 0.1;
return function (px, py, u, v) {
if (v < line) { return inner(px, py, u, v * (0.82 / line)); }
var d = (v - line) / (1 - line);
var ripple = (n.fbm(u * 8, v * 90, 3) - 0.5) * (0.012 + d * 0.06);
var mv = line - (v - line) * 1.05 + ripple;
var mpx = clamp(Math.round(px + ripple * w * 0.7), 0, w - 1);
var c = inner(mpx, py, clamp(mpx / w, 0, 1), clamp(mv, 0, 1) * (0.82 / line));
return mix(scale(c, 0.8), [26, 46, 62], 0.14 + d * 0.3);
};
}
function sea(w, h, r, n) {
var s = SKIES[[0, 2, 2, 3][Math.floor(r() * 4)]], aspect = w / h;
var line = 0.5 + r() * 0.14, sunU = 0.3 + r() * 0.4, sunV = line - 0.05 - r() * 0.12;
var deep = [18 + r() * 12, 44 + r() * 20, 72 + r() * 24];
return function (px, py, u, v) {
if (v < line) { return skyColor(n, s, u, v / line * 0.96, sunU, sunV / line, aspect, 0.9); }
var d = (v - line) / (1 - line), persp = 1 / (d + 0.035);
var wave = n.fbm(u * aspect * persp * 1.3, persp * 2.4, 4);
var c = mix(mix(s.low, deep, smooth(0, 0.34, d)), scale(deep, 0.6), d);
c = scale(c, 0.76 + wave * 0.5);
var path = Math.abs(u - sunU) * aspect / (0.05 + d * 0.32);
var glint = Math.exp(-path * path) * smooth(0.54, 0.72, wave);
return add(c, s.sun, glint * 0.95);
};
}
function dunes(w, h, r, n) {
var s = SKIES[[0, 1, 2, 1][Math.floor(r() * 4)]], aspect = w / h, L = 4, lines = [], i;
var sand = [206 + r() * 30, 146 + r() * 24, 86 + r() * 26];
for (i = 0; i < L; i++) {
lines.push(new Float32Array(w));
var off = r() * 50, base = 0.42 + i * 0.15;
for (var x = 0; x < w; x++) {
lines[i][x] = base - 0.11 * Math.sin(x / w * (2.2 + i) * aspect + off) - 0.09 * (n.fbm(x / w * 1.7 * aspect + off, i * 3.1, 3) - 0.5);
}
}
return function (px, py, u, v) {
for (var l = L - 1; l >= 0; l--) {
if (v >= lines[l][px]) {
var slope = lines[l][clamp(px + 2, 0, w - 1)] - lines[l][clamp(px - 2, 0, w - 1)];
var below = v - lines[l][px];
var side = clamp(0.56 + slope * 95 - below * 0.8, 0.16, 1.14);
var ripples = 0.95 + 0.07 * Math.sin((v * 310 + n.fbm(u * 5 * aspect, v * 8, 3) * 26));
var c = scale(sand, side * ripples);
return mix(c, s.haze, (1 - l / (L - 1)) * 0.34);
}
}
return skyColor(n, s, u, v * 1.05, 0.72, 0.2, aspect, 0.2);
};
}
function forest(w, h, r, n) {
var s = SKIES[[0, 1, 3, 1][Math.floor(r() * 4)]], aspect = w / h, L = 6, rows = [], i;
var green = [26 + r() * 16, 56 + r() * 26, 42 + r() * 18];
for (i = 0; i < L; i++) {
var line = new Float32Array(w), base = 0.36 + i * 0.1, off = r() * 40;
line.fill(base - 0.012 * n.fbm(off, i, 2));
// Each tree is its own tapered, jagged cone, so spacing and height vary.
var cx = -0.05 * w;
while (cx < w * 1.05) {
var hgt = (0.11 + i * 0.038) * (0.55 + 0.6 * r());
var half = hgt * h * (0.2 + r() * 0.1);
var tiers = 6 + Math.floor(r() * 5), phase = r() * 6;
var from = Math.max(0, Math.floor(cx - half)), to = Math.min(w - 1, Math.ceil(cx + half));
for (var x = from; x <= to; x++) {
var q = 1 - Math.abs(x - cx) / half;
if (q <= 0) { continue; }
var teeth = 0.8 + 0.2 * Math.abs(Math.sin(q * tiers * 1.6 + phase));
var top = base - hgt * Math.pow(q, 1.25) * teeth;
if (top < line[x]) { line[x] = top; }
}
cx += half * (0.45 + r() * 0.95);
}
rows.push(line);
}
return function (px, py, u, v) {
for (var l = L - 1; l >= 0; l--) {
if (v >= rows[l][px]) {
var depth = l / (L - 1);
var c = scale(green, 0.42 + 0.9 * n.fbm(u * 60, v * 60, 3) * depth + 0.2);
var fog = (1 - depth) * 0.86 + 0.16 * n.fbm(u * 3 + l, v * 7, 4);
return mix(c, mix(s.low, s.haze, 0.45), clamp(fog, 0, 0.94));
}
}
return mix(skyColor(n, s, u, v, 0.5, 0.15, aspect, 0.25), s.low, 0.35);
};
}
function fields(w, h, r, n) {
var s = SKIES[[1, 0, 1, 2][Math.floor(r() * 4)]], aspect = w / h;
var line = 0.34 + r() * 0.12, colors = [[120, 152, 58], [186, 168, 72], [86, 126, 56], [156, 134, 62], [198, 190, 104]];
var bend = r() * 7, hillSeed = r() * 30;
return function (px, py, u, v) {
var horizon = line - 0.06 * (n.fbm(u * 2.4 * aspect + hillSeed, 1.2, 4) - 0.5);
if (v < horizon) { return skyColor(n, s, u, v / horizon * 0.92, 0.72, 0.28, aspect, 1); }
var d = (v - horizon) / (1 - horizon), persp = 1 / (d + 0.06);
var fu = (u - 0.5) * aspect * persp * 0.55 + Math.sin(d * 3 + bend) * 0.5;
var fv = persp * 0.8;
var warp = n.fbm(fu * 0.6, fv * 0.6, 3) * 1.2;
var cell = Math.floor(fu + warp) * 7 + Math.floor(fv + warp * 0.6) * 13;
var base = colors[Math.abs(cell) % colors.length];
var rows = 0.92 + 0.11 * Math.sin((fu + warp) * (24 + (Math.abs(cell) % 3) * 12));
var c = scale(base, rows * (0.72 + n.fbm(u * 28, v * 34, 4) * 0.58));
return mix(c, s.haze, Math.pow(1 - d, 5) * 0.66);
};
}
function cloudscape(w, h, r, n) {
var s = SKIES[Math.floor(r() * 3)], aspect = w / h, sunU = r(), off = r() * 40;
return function (px, py, u, v) {
var sky = mix(s.top, s.low, Math.pow(v, 1.3));
var x = u * 2.4 * aspect + off, y = v * 3.6 + off * 0.3;
var warp = n.fbm(x * 0.8, y * 0.8, 3);
var density = n.fbm(x + warp, y + warp * 0.8, 7) + v * 0.3 - 0.13;
var lightProbe = n.fbm(x + warp - 0.09, y + warp * 0.8 - 0.12, 5) + v * 0.3 - 0.13;
var k = smooth(0.44, 0.68, density);
var lit = clamp(0.62 + (density - lightProbe) * 5.2, 0.16, 1.2);
var cloud = mix(scale(s.haze, 0.6), mix([255, 252, 246], s.sun, 0.36), lit);
var glow = Math.exp(-Math.abs(u - sunU) * 2.4) * 0.14;
return add(mix(sky, cloud, k), s.sun, glow);
};
}
function nightSky(w, h, r, n) {
var aspect = w / h, tilt = 0.3 + r() * 0.9, off = r() * 20;
var ridge = ridgeLine(n, w, 0.86, 0.22, 2.5 * aspect, r() * 40);
var stars = new Float32Array(w * h), count = Math.floor(w * h / 190), i;
for (i = 0; i < count; i++) {
var at = Math.floor(r() * w) + Math.floor(r() * h) * w;
stars[at] = Math.pow(r(), 3.4) * 1.4 + 0.1;
}
return function (px, py, u, v) {
if (v >= ridge[px]) { return scale([12, 16, 22], 0.5 + n.fbm(u * 30, v * 30, 3) * 0.5); }
var c = mix([7, 11, 30], [32, 42, 76], Math.pow(v, 2.1));
var band = (v - 0.45) * Math.cos(tilt) - (u - 0.5) * aspect * Math.sin(tilt) * 0.5;
var along = (u - 0.5) * aspect * Math.cos(tilt) + (v - 0.45) * Math.sin(tilt);
var cloud = n.fbm(along * 3.2 + off, band * 8 + off, 6);
var m = Math.exp(-band * band * 26) * smooth(0.28, 0.72, cloud);
c = add(c, [172, 152, 182], m * 0.78);
c = add(c, [255, 208, 170], Math.exp(-band * band * 110) * smooth(0.45, 0.8, cloud) * 0.34);
var star = stars[px + py * w];
if (star > 0) { c = add(c, [255, 246, 232], Math.min(star * (1 + m), 1)); }
return add(c, [255, 150, 96], Math.exp(-(ridge[px] - v) * 13) * 0.11);
};
}
function aurora(w, h, r, n) {
var aspect = w / h, off = r() * 30, hue = r();
var ridge = ridgeLine(n, w, 0.62, 0.12, 2.1 * aspect, r() * 40);
var line = 0.7, stars = prng(77 + Math.floor(off * 9));
var green = [76, 246, 150], top = hue > 0.5 ? [150, 92, 232] : [60, 180, 226];
var field = new Float32Array(w * h), count = Math.floor(w * h / 420), i;
for (i = 0; i < count; i++) { field[Math.floor(stars() * w * h)] = stars() * 0.8; }
function air(px, py, u, v) {
var c = mix([6, 12, 30], [20, 44, 64], Math.pow(v / line, 1.6));
for (var b = 0; b < 3; b++) {
var center = 0.25 + b * 0.13 + 0.12 * Math.sin(u * 3.4 * aspect + off + b * 2) + 0.07 * (n.fbm(u * 3 * aspect + b, off, 4) - 0.5) * 3;
var dy = v - center;
var rays = 0.5 + 0.5 * n.fbm(u * 46 * aspect + b * 9, off + b, 3);
var below = Math.exp(-Math.max(dy, 0) * 34), above = Math.exp(-Math.max(-dy, 0) * 7.5);
var k = below * above * Math.pow(rays, 2.1) * 1.9;
c = add(c, mix(green, top, clamp(-dy * 6.4, 0, 1)), k * 0.62);
}
var star = field[px + py * w];
return star > 0 ? add(c, [240, 244, 255], star) : c;
}
return function (px, py, u, v) {
if (v >= line) {
var d = (v - line) / (1 - line);
var wob = (n.fbm(u * 7, v * 80, 3) - 0.5) * (0.02 + d * 0.05);
var my = clamp(line - (v - line) * 1.1 + wob, 0, line - 0.001);
var mx = clamp(Math.round(px + wob * w), 0, w - 1);
var rc = my >= ridge[mx] ? [8, 12, 18] : air(mx, Math.floor(my * h), mx / w, my);
return mix(scale(rc, 0.72), [6, 14, 24], 0.2 + d * 0.3);
}
return v >= ridge[px] ? scale([9, 14, 20], 0.5 + n.fbm(u * 25, v * 25, 3) * 0.6) : air(px, py, u, v);
};
}
function stones(w, h, r, n) {
var aspect = w / h, cells = 15 + Math.floor(r() * 8), pts = [], i;
var tones = [[146, 136, 124], [98, 92, 88], [182, 170, 150], [122, 112, 106], [166, 128, 104], [80, 88, 96]];
for (i = 0; i < cells * cells; i++) {
pts.push({ x: (i % cells + 0.15 + r() * 0.7) / cells * aspect, y: (Math.floor(i / cells) + 0.15 + r() * 0.7) / cells, tone: tones[Math.floor(r() * tones.length)], k: 0.76 + r() * 0.42 });
}
return function (px, py, u, v) {
var x = u * aspect + (n.fbm(u * 8, v * 8, 2) - 0.5) * 0.03;
var y = v + (n.fbm(u * 8 + 5, v * 8, 2) - 0.5) * 0.03;
var cx = Math.floor(x / aspect * cells), cy = Math.floor(y * cells);
var best = 9, second = 9, pick = pts[0];
for (var a = -2; a <= 2; a++) {
for (var b = -2; b <= 2; b++) {
var q = pts[clamp(cy + b, 0, cells - 1) * cells + clamp(cx + a, 0, cells - 1)];
var d = (q.x - x) * (q.x - x) + (q.y - y) * (q.y - y);
if (d < best) { second = best; best = d; pick = q; }
else if (d < second && q !== pick) { second = d; }
}
}
var edge = Math.sqrt(second) - Math.sqrt(best);
if (edge < 0.0045) { return [18, 16, 15]; }
var dome = smooth(0.003, 0.038, edge);
var nx = (pick.x - x) * cells, ny = (pick.y - y) * cells;
var light = clamp(0.56 + dome * 0.3 + (nx * 0.34 + ny * 0.44), 0.16, 1.32);
var speck = 0.86 + n.fbm(x * 70, y * 70, 4) * 0.32;
return scale(pick.tone, pick.k * light * speck * (0.5 + 0.5 * dome));
};
}
function bokeh(w, h, r, n) {
var aspect = w / h, discs = [], i, palette = [[255, 196, 92], [255, 118, 96], [148, 214, 118], [255, 232, 170], [116, 190, 226]];
var bgA = [26 + r() * 24, 46 + r() * 30, 34 + r() * 24], bgB = [82 + r() * 40, 96 + r() * 36, 58 + r() * 26];
for (i = 0; i < 46; i++) {
discs.push({ x: r() * aspect, y: r(), r: 0.025 + r() * r() * 0.095, c: palette[Math.floor(r() * palette.length)], a: 0.1 + r() * 0.32 });
}
var stemX = 0.25 + r() * 0.5, lean = (r() - 0.5) * 0.5, budY = 0.26 + r() * 0.2;
return function (px, py, u, v) {
var x = u * aspect;
var c = mix(bgA, bgB, n.fbm(u * 2.4 * aspect, v * 2.4, 4));
for (var d = 0; d < discs.length; d++) {
var o = discs[d], dist = Math.sqrt((o.x - x) * (o.x - x) + (o.y - v) * (o.y - v));
if (dist < o.r) {
c = add(c, o.c, o.a * (0.72 + 0.28 * smooth(o.r * 0.72, o.r, dist)) * smooth(o.r, o.r * 0.95, dist));
}
}
var sx = (stemX + lean * (1 - v) * (1 - v)) * aspect;
if (v > budY && Math.abs(x - sx) < 0.0065) { return mix([56, 104, 48], [112, 158, 72], (x - sx) / 0.013 + 0.5); }
var bx = x - (stemX + lean * (1 - budY) * (1 - budY)) * aspect, by = v - budY;
var ang = Math.atan2(by, bx), rad = Math.sqrt(bx * bx + by * by);
var petal = 0.062 * (0.74 + 0.26 * Math.abs(Math.cos(ang * 3.5)));
if (rad < petal) {
if (rad < 0.017) { return mix([244, 196, 60], [176, 104, 34], n.at(x * 300, v * 300)); }
return scale([246, 232, 226], 0.7 + 0.36 * (rad / petal) * (0.7 + 0.3 * Math.cos(ang * 7)));
}
return c;
};
}
function skyline(w, h, r, n) {
var s = SKIES[[2, 3, 3, 0][Math.floor(r() * 4)]], aspect = w / h;
var line = 0.7 + r() * 0.06, rows = [], layer, x;
for (layer = 0; layer < 3; layer++) {
var tops = new Float32Array(w), id = new Int32Array(w), at = 0, k = 0;
while (at < w) {
var bw = Math.floor((0.03 + r() * 0.055) * w * (1 + layer * 0.5));
var top = line - (0.1 + layer * 0.06) - r() * (0.11 + layer * 0.12);
for (x = at; x < Math.min(w, at + bw); x++) { tops[x] = top; id[x] = k; }
at += bw; k++;
}
rows.unshift({ tops: tops, id: id, shade: 0.3 + (2 - layer) * 0.2 });
}
function city(px, py, u, v) {
for (var l = 2; l >= 0; l--) {
var row = rows[l];
if (v >= row.tops[px] && v < line) {
var c = mix([18, 18, 34], s.haze, (2 - l) * 0.21);
var wx = Math.floor(px / 4), wy = Math.floor(py / 5);
if (px % 4 !== 0 && py % 5 > 1 && n.at(wx * 3.3 + row.id[px], wy * 2.9 + l * 5) > 0.67) {
var lamp = n.at(wx * 7.1, wy * 5.7) > 0.5 ? [255, 214, 136] : [186, 216, 240];
c = mix(c, lamp, 0.92 - (2 - l) * 0.16);
}
return c;
}
}
return skyColor(n, s, u, v / line * 0.94, 0.68, 0.46, aspect, 0.7);
}
return function (px, py, u, v) {
if (v < line) { return city(px, py, u, v); }
var d = (v - line) / (1 - line);
var wob = (n.fbm(u * 9, v * 110, 3) - 0.5) * (0.015 + d * 0.05);
var mv = clamp(line - (v - line) * 1.05 + wob, 0, line - 0.001);
var mx = clamp(Math.round(px + wob * w * 0.6), 0, w - 1);
return mix(scale(city(mx, Math.floor(mv * h), mx / w, mv), 0.7), [10, 18, 34], 0.16 + d * 0.32);
};
}
var SCENES = [mountains, sea, stones, forest, cloudscape, lake, dunes, bokeh, nightSky, fields, aurora, skyline];
var NAMES = ['Ridges', 'Open water', 'River stones', 'Fog in the pines', 'Cloud bank', 'Still lake', 'Dunes', 'Garden light', 'Night sky', 'Farmland', 'Aurora', 'Harbor city'];
/**
* Renders one picture.
* @return {Uint8ClampedArray} RGBA pixels, w * h * 4 long
*/
function renderPhotograph(index, w, h) {
var seed = 40961 + index * 7919;
var r = prng(seed);
var n = new Noise(seed ^ 0x5bd1e995);
var shade = SCENES[index % SCENES.length](w, h, r, n);
var grainRnd = prng(seed + 3);
var warm = (r() - 0.5) * 0.07, contrast = 1.04 + r() * 0.1;
var out = new Uint8ClampedArray(w * h * 4);
var i = 0;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var u = (x + 0.5) / w, v = (y + 0.5) / h;
var c = shade(x, y, u, v);
var dx = u - 0.5, dy = v - 0.5;
var vignette = 1 - 0.62 * Math.pow(dx * dx + dy * dy, 1.15);
var grain = (grainRnd() + grainRnd() - 1) * 5.2;
for (var k = 0; k < 3; k++) {
var value = c[k] * vignette * (k === 0 ? 1 + warm : (k === 2 ? 1 - warm : 1)) / 255;
value = clamp(0.5 + (value - 0.5) * contrast, 0, 1);
value = value * value * (3 - 2 * value) * 0.34 + value * 0.66;
out[i + k] = value * 255 + grain;
}
out[i + 3] = 255;
i += 4;
}
}
return out;
}
root.ProceduralPhotographs = {
renderPhotograph: renderPhotograph,
titleFor: function (index) {
return NAMES[index % NAMES.length] + ' ' + (Math.floor(index / NAMES.length) + 1);
},
/* Every sixth picture is a portrait. */
isPortrait: function (index) { return index % 6 === 5; }
};
})(typeof window !== 'undefined' ? window : globalThis);
/res/2.0/scripts/tools/magnifier.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
var yui = yui || YAHOO;
sw.tools = sw.tools || {};
/**
* Provides a magnifying function and returns the modified position
* and size of a given point.
*
* Inspired by Jared Tarbel's text sphere:
* http://www.levitated.net/daily/levTextSphere.html
*
* @param radius the magnifier's radius.
* @param x the magnifier's x position
* @param y the magnifier's y position
* @param maxMagnification the magnifier's maximum magnification (at
* it's center position).
* @param minMagnification the magnifier's minimum magnification (at
* it's center position).
* @param direction one of <code>DIRECTION_BOTH</code>, <code>DIRECTION_X</code>
* <code>DIRECTION_Y</code>
*/
sw.tools.Magnifier = function (radius, x, y,
maxMagnification,
minMagnification,
direction) {
this.radius = radius;
this.x = x;
this.y = y;
this.maxMagnification = maxMagnification;
this.minMagnification = minMagnification;
this.direction = direction;
this.events = {
onChange: new yui.util.CustomEvent(this.MAGNIFIER_CHANGE)
}
}
/**
* Constants
*/
sw.tools.Magnifier.prototype.MAGNIFIER_CHANGE = "MAGNIFIER_CHANGE";
sw.tools.Magnifier.prototype.DIRECTION_BOTH = 0;
sw.tools.Magnifier.prototype.DIRECTION_X = 1;
sw.tools.Magnifier.prototype.DIRECTION_Y= 2;
/**
* Sets the current radius
*
* @param newRadius the new magnifier radius
*/
sw.tools.Magnifier.prototype.setRadius = function (newRadius) {
if (this.radius !== newRadius) {
this.radius = newRadius;
this.events.onChange.fire();
}
}
/**
* Change the magnifier position.
*/
sw.tools.Magnifier.prototype.setPosition = function (x, y) {
this.x = x;
this.y = y;
this.events.onChange.fire();
}
/**
* Computes the displacement for the given point.
*
* @param x the input point's x coordinate
* @param y the input point's y coordinate
* @param result an object where the displaced coordinates and magnification
* factor will be stored.
*/
sw.tools.Magnifier.prototype.processPoint = function (x, y, result) {
var dx = x - this.x;
var dy = y - this.y;
var displacement;
var d = Math.sqrt(dx * dx + dy * dy);
var p = d / this.radius;
if (p >= 1) {
result.x = x;
result.y = y;
result.magnification = this.minMagnification;
result.displacement = 0;
result.p = 1;
} else {
// On the edge of the magnifier, there is no displacement.
// There is no displacement at the center either.
// The maximum displacement is half way (p = 0.5) between
// the edge of the lens and its center.
displacement = Math.sin(Math.PI * p);
result.x = x + dx * displacement;
result.y = y + dy * displacement;
// The maximum magnification is reached at the center of the lens (p = 0).
// On the edge (p = 1), the magnification is 1 (no magnification).
result.magnification = this.minMagnification +
(this.maxMagnification - this.minMagnification) *
(1 - Math.sin(p * Math.PI / 2));
result.displacement = displacement;
result.p = p;
}
switch (this.direction) {
case this.DIRECTION_X: {
result.y = y;
break;
}
case this.DIRECTION_Y: {
result.x = x;
break;
}
default:
break;
}
}/res/2.0/scripts/animation/animate.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
(function () {
sw.animation = sw.animation || {};
yui = YAHOO;
var Anim = yui.util.Anim;
/**
* Object with the names of the transform pseudo attributes.
*/
var PSEUDO_ATTRIBUTES = {
tx: "#tx",
ty: "#ty",
sx: "#sx",
sy: "#sy",
r: "#r"
};
var PSEUDO_DEFAULTS = {
tx: 0,
ty: 0,
sx: 1,
sy: 1,
r: 0
};
var PSEUDO_ATTRIBUTES_ARRAY = ["tx", "ty", "sx", "sy", "r"];
var N_PSEUDO_ATTRIBUTES = PSEUDO_ATTRIBUTES_ARRAY.length;
/**
* Simple extension of the YUI animation classes to handle SVG transforms.
*
* The extension handles the "r", "sx", "sy", "tx" and "ty" pseudo attributes
* by manipulating the transform of the target element using a template.
*
* @param p_el the element that will be animated
* @param p_attributes the attributes to animate. This animation class adds the
* "r" (rotation), "tx", "ty", "sx" and "sy" (scale) pseudo-attributes.
* @param p_oTransformTemplate the template for the transform attribute to
* animate. By default, it is
* "translate(#tx,#ty) scale(#sx,#sy) rotate(#r)"
* but it can be set to any string.
* @param p_oDuration the animation duration
* @param p_oMethod easing method
*
* @see http://developer.yahoo.com/yui/docs/YAHOO.util.Anim.html
*/
sw.animation.Animate = function (p_el, p_attributes,
p_oDuration,
p_oMethod) {
sw.animation.Animate.superclass.constructor.call(this, p_el,
p_attributes, p_oDuration, p_oMethod);
var el = sw.stringToElement(p_el);
var _endCallbacks = [];
var _endAnimations = [];
var _beginCallbacks = [];
var _beginAnimations = [];
this._endCallbacks = _endCallbacks;
this._endAnimations = _endAnimations;
this._beginCallbacks = _beginCallbacks;
this._beginAnimations = _beginAnimations;
this.onComplete.subscribe(function () {
for (var i = 0; i < _endCallbacks.length; i++) {
_endCallbacks[i]();
}
for (i = 0; i < _endAnimations.length; i++) {
_endAnimations[i].animate();
}
});
this.onStart.subscribe(function () {
for (var i = 0; i < _beginCallbacks.length; i++) {
_beginCallbacks[i]();
}
for (i = 0; i < _beginAnimations.length; i++) {
_beginAnimations[i].animate();
}
});
};
yui.lang.extend(sw.animation.Animate,
Anim, {
/**
* Sets the new attribute value
*
* @param p_attr the attribute name
* @param p_val the attribute value
* @param p_unit the unit
*/
setAttribute : function (p_attr, p_val, p_unit) {
var el = this.getEl();
if (attributeHandlers[p_attr] &&
attributeHandlers[p_attr].setAttribute) {
return attributeHandlers[p_attr].setAttribute.call(this, el, p_val);
} else {
// Let the base class handle the attributes
sw.animation.Animate.superclass.setAttribute.call(this,
p_attr, p_val, p_unit);
}
},
/**
* Gets the attribute value
*
* @param p_attr the attribute name
*/
getAttribute : function (p_attr) {
if (attributeHandlers[p_attr] &&
attributeHandlers[p_attr].getAttribute) {
return attributeHandlers[p_attr].getAttribute.call(this, this.getEl());
} else {
// Let the base class handle the attribute
return sw.animation.Animate.superclass.
getAttribute.call(this, p_attr);
}
},
/**
* Overrides the default implementation to check if there is an attribute
* handler for the attribute.
* @param {String} attr The name of the attribute.
* @param {Number} start The value this attribute should start from for this animation.
* @param {Number} end The value this attribute should end at for this animation.
* @return The Value to be applied to the attribute.
*/
doMethod : function (attr, start, end) {
var val;
if (attributeHandlers[attr] &&
attributeHandlers[attr].interpolate) {
var p = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
val = attributeHandlers[attr].interpolate.call(this, start, end, p);
} else {
val = Anim.prototype.doMethod.call(this, attr, start, end);
}
return val;
},
/**
* Implementation helper: applies the current transform.
* Note that this quite costly, from a computation perspective, so
* it should be use conservatively.
*/
applyTransform : function () {
var txf = this.transformTemplate;
var el = this.getEl();
var attrs = PSEUDO_ATTRIBUTES;
var a = PSEUDO_ATTRIBUTES_ARRAY;
var n = a.length;
var p;
for (var i = 0; i < n; i++) {
p = a[i];
txf = txf.replace(attrs[p], el[p]);
}
el.setAttribute("transform", txf);
},
/**
* Returns a handler that will start this animation instance when invoked.
*/
getStartHandler : function () {
var that = this;
if (this._startHandler === undefined) {
this._startHandler = function () {
that.animate();
};
}
return this._startHandler;
},
/**
* Adds a function of animation to call or play when this animation ends
*
* @param p_animOrCallback an animation or function to trigger when this
* animation ends
*/
onEnd : function (p_animOrCallback) {
if (typeof p_animOrCallback === "function") {
this._endCallbacks.push(p_animOrCallback);
} else if (p_animOrCallback !== null &&
p_animOrCallback !== undefined &&
typeof p_animOrCallback.animate === "function") {
this._endAnimations.push(p_animOrCallback);
}
},
/**
* Adds a function of animation to call or play when this animation begins
*
* @param p_animOrCallback an animation or function to trigger when this
* animation begins
*/
onBegin : function (p_animOrCallback) {
if (typeof p_animOrCallback === "function") {
this._beginCallbacks.push(p_animOrCallback);
} else if (p_animOrCallback !== null &&
p_animOrCallback !== undefined &&
typeof p_animOrCallback.animate === "function") {
this._beginAnimations.push(p_animOrCallback);
}
}
});
/**
* Class static
*/
var attributeHandlers = {};
/**
* Adds a new way to handle a given attribute. The handler should have the
* following:
*
* - setAttribute. A funtion taking the element and value as parameters.
* - getAttribute. A function taking the element as parameter and
* returning the attribute value.
* - interpolate. A function taking the start value, end value, current
* progress in time interval and interpolation method as a parameter. It
* should return the value to apply to the animation target.
*
* @param p_attributeName the name of the attribute to which the handler
* applies.
* @param p_attributeHandler an object holding the setAttribute, getAttribute
* and interpolate methods
*/
sw.animation.Animate.addAttributeHandler = function (p_attributeName,
p_attributeHandler) {
attributeHandlers[p_attributeName] = p_attributeHandler;
};
// =============================================================================
// Generic handler for the SVG transform attribute
// =============================================================================
sw.animation.Animate.addAttributeHandler("txf", {
setAttribute: function (e, v) {
var txf = this.attributes.txf.template, val, p;
if (txf) {
for (var p in v) {
if (v.hasOwnProperty(p)) {
val = v[p];
txf = txf.replace(PSEUDO_ATTRIBUTES[p], val);
e[p] = val;
}
}
e.setAttribute("transform", txf);
}
},
getAttribute: function (e) {
var result = {
tx: 0,
ty: 0,
sx: 1,
sy: 1,
r: 0
};
for (var i = 0; i < N_PSEUDO_ATTRIBUTES; i++) {
a = PSEUDO_ATTRIBUTES_ARRAY[i];
if (e[a] !== undefined) {
result[a] = e[a];
} else {
e[a] = result[a];
}
}
return result;
},
interpolate: function (start, end, p) {
var s, e, a, result = {}, elt;
for (var i = 0; i < N_PSEUDO_ATTRIBUTES; i++) {
a = PSEUDO_ATTRIBUTES_ARRAY[i];
s = start[a];
e = end[a];
if (s === undefined) {
elt = this.getEl();
if (elt[a] !== undefined) {
s = elt[a];
}
if (s === undefined) {
s = PSEUDO_DEFAULTS[a];
}
start[a] = s;
}
if (e !== undefined) {
result[a] = p * e + (1 - p) * s;
} else {
result[a] = s;
}
}
return result;
}
});
})();