Making a sample for shadow maps for more intensive development

Merge branch 'shadow-gm' into shadow-sample

Added variable size shadow maps. Also fixed some bugs

BUG=skia:
GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=2198933002

Review-Url: https://codereview.chromium.org/2198933002
diff --git a/gm/shadowmaps.cpp b/gm/shadowmaps.cpp
index 4a0f88e..1ae95fb 100644
--- a/gm/shadowmaps.cpp
+++ b/gm/shadowmaps.cpp
@@ -7,9 +7,9 @@
 
 
 #include "gm.h"
-#include "SkPaintFilterCanvas.h"
 #include "SkPathEffect.h"
 #include "SkPictureRecorder.h"
+#include "SkShadowPaintFilterCanvas.h"
 #include "SkShadowShader.h"
 #include "SkSurface.h"
 
@@ -72,210 +72,6 @@
 
 namespace skiagm {
 
-/*  We override the onFilter method to draw depths into the canvas
- *  depending on the current draw depth of the canvas, throwing out
- *  the actual draw color.
- */
-class SkShadowPaintFilterCanvas : public SkPaintFilterCanvas {
-public:
-
-    SkShadowPaintFilterCanvas(SkCanvas* canvas) : INHERITED(canvas) { }
-
-    // TODO use a shader instead
-    bool onFilter(SkTCopyOnFirstWrite<SkPaint>* paint, Type type) const override {
-        if (*paint) {
-            int z = this->getZ();
-            SkASSERT(z <= 0xFF && z >= 0x00);
-
-            SkPaint newPaint;
-            newPaint.setPathEffect(sk_ref_sp<SkPathEffect>((*paint)->getPathEffect()));
-
-            SkColor color = 0xFF000000; // init color to opaque black
-            color |= z; // Put the index into the blue component
-            newPaint.setColor(color);
-
-            *paint->writable() = newPaint;
-        }
-
-        return true;
-    }
-
-    void onDrawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint) {
-        SkTCopyOnFirstWrite<SkPaint> filteredPaint(paint);
-        if (this->onFilter(&filteredPaint, kPicture_Type)) {
-            // we directly call SkCanvas's onDrawPicture because calling the one
-            // that INHERITED has (SkPaintFilterCanvas) leads to wrong behavior
-            this->SkCanvas::onDrawPicture(picture, matrix, filteredPaint);
-        }
-    }
-
-    void updateMatrix() {
-        this->save();
-
-        // When we use the SkShadowPaintFilterCanvas, we can only render
-        // one depth map at a time. Thus, we leave it up to the user to
-        // set SkLights to only contain (or contain at the first position)
-        // the light they intend to use for the current depth rendering.
-
-        if (fLights->numLights() > 0 &&
-            this->fLights->light(0).type() == SkLights::Light::kDirectional_LightType) {
-            SkVector3 lightDir = this->fLights->light(0).dir();
-            SkScalar x = lightDir.fX * this->getZ();
-            SkScalar y = lightDir.fY * this->getZ();
-
-            this->translate(x, y);
-        }
-
-    }
-
-    void onDrawPaint(const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawPaint(paint);
-        this->restore();
-    }
-
-    void onDrawPoints(PointMode mode, size_t count, const SkPoint pts[],
-                      const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawPoints(mode, count, pts, paint);
-        this->restore();
-    }
-
-    void onDrawRect(const SkRect& rect, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawRect(rect, paint);
-        this->restore();
-    }
-
-    void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawRRect(rrect, paint);
-        this->restore();
-    }
-
-    void onDrawDRRect(const SkRRect& outer, const SkRRect& inner,
-                      const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawDRRect(outer, inner, paint);
-        this->restore();
-    }
-
-    void onDrawOval(const SkRect& rect, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawOval(rect, paint);
-        this->restore();
-    }
-
-    void onDrawPath(const SkPath& path, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawPath(path, paint);
-        this->restore();
-    }
-
-    void onDrawBitmap(const SkBitmap& bm, SkScalar left, SkScalar top,
-                      const SkPaint* paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawBitmap(bm, left, top, paint);
-        this->restore();
-    }
-
-    void onDrawBitmapRect(const SkBitmap& bm, const SkRect* src, const SkRect& dst,
-                          const SkPaint* paint, SrcRectConstraint constraint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawBitmapRect(bm, src, dst, paint, constraint);
-        this->restore();
-    }
-
-    void onDrawBitmapNine(const SkBitmap& bm, const SkIRect& center,
-                          const SkRect& dst, const SkPaint* paint) {
-        this->updateMatrix();
-        this->INHERITED::onDrawBitmapNine(bm, center, dst, paint);
-        this->restore();
-    }
-
-    void onDrawImage(const SkImage* image, SkScalar left, SkScalar top,
-                     const SkPaint* paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawImage(image, left, top, paint);
-        this->restore();
-    }
-
-    void onDrawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
-                         const SkPaint* paint, SrcRectConstraint constraint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawImageRect(image, src, dst, paint, constraint);
-        this->restore();
-    }
-
-    void onDrawImageNine(const SkImage* image, const SkIRect& center,
-                         const SkRect& dst, const SkPaint* paint) {
-        this->updateMatrix();
-        this->INHERITED::onDrawImageNine(image, center, dst, paint);
-        this->restore();
-    }
-
-    void onDrawVertices(VertexMode vmode, int vertexCount, const SkPoint vertices[],
-                        const SkPoint texs[], const SkColor colors[], SkXfermode* xmode,
-                        const uint16_t indices[], int indexCount, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawVertices(vmode, vertexCount, vertices, texs, colors,
-                                        xmode, indices, indexCount, paint);
-        this->restore();
-    }
-
-    void onDrawPatch(const SkPoint cubics[], const SkColor colors[], const SkPoint texCoords[],
-                     SkXfermode* xmode, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawPatch(cubics, colors, texCoords, xmode, paint);
-        this->restore();
-    }
-
-    void onDrawText(const void* text, size_t byteLength,
-                    SkScalar x, SkScalar y, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawText(text, byteLength, x, y, paint);
-        this->restore();
-    }
-
-    void onDrawPosText(const void* text, size_t byteLength,
-                       const SkPoint pos[], const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawPosText(text, byteLength, pos, paint);
-        this->restore();
-    }
-
-    void onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
-                        SkScalar constY, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawPosTextH(text, byteLength, xpos, constY, paint);
-        this->restore();
-    }
-
-    void onDrawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
-                          const SkMatrix* matrix, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawTextOnPath(text, byteLength, path, matrix, paint);
-        this->restore();
-    }
-
-    void onDrawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
-                           const SkRect* cull, const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawTextRSXform(text, byteLength, xform, cull, paint);
-        this->restore();
-    }
-
-    void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
-                        const SkPaint& paint) override {
-        this->updateMatrix();
-        this->INHERITED::onDrawTextBlob(blob, x, y, paint);
-        this->restore();
-    }
-
-private:
-    typedef SkPaintFilterCanvas INHERITED;
-};
-
 class ShadowMapsGM : public GM {
 public:
     ShadowMapsGM() {
@@ -322,7 +118,11 @@
             // TODO: compute the correct size of the depth map from the light properties
             // TODO: maybe add a kDepth_8_SkColorType
 
-            SkImageInfo info = SkImageInfo::Make(kWidth, kHeight,
+            // TODO: find actual max depth of picture
+            SkISize shMapSize = SkShadowPaintFilterCanvas::
+                    ComputeDepthMapSize(fLights->light(i), 255, kWidth, kHeight);
+
+            SkImageInfo info = SkImageInfo::Make(shMapSize.fWidth, shMapSize.fHeight,
                                                  kBGRA_8888_SkColorType,
                                                  kOpaque_SkAlphaType);
 
diff --git a/gyp/SampleApp.gyp b/gyp/SampleApp.gyp
index beaaeca..d7a2126 100644
--- a/gyp/SampleApp.gyp
+++ b/gyp/SampleApp.gyp
@@ -103,6 +103,7 @@
             '../experimental/iOSSampleApp/iPhone',
             '../experimental/iOSSampleApp/Shared',
             '../include/utils/ios',
+            '../src/utils',
             '../src/views/mac',
           ],
           'xcode_settings' : {
diff --git a/gyp/samples.gypi b/gyp/samples.gypi
index 7e9c414..eacf3fd 100644
--- a/gyp/samples.gypi
+++ b/gyp/samples.gypi
@@ -88,6 +88,7 @@
     '../samplecode/SampleRepeatTile.cpp',
     '../samplecode/SampleShaders.cpp',
     '../samplecode/SampleShaderText.cpp',
+    '../samplecode/SampleShadowing.cpp',
     '../samplecode/SampleShip.cpp',
     '../samplecode/SampleSkLayer.cpp',
     '../samplecode/SampleSlides.cpp',
diff --git a/gyp/utils.gypi b/gyp/utils.gypi
index 4903f3d..f23203c 100644
--- a/gyp/utils.gypi
+++ b/gyp/utils.gypi
@@ -67,6 +67,8 @@
         '<(skia_src_path)/utils/SkPatchUtils.h',
         '<(skia_src_path)/utils/SkRGBAToYUV.cpp',
         '<(skia_src_path)/utils/SkRGBAToYUV.h',
+        '<(skia_src_path)/utils/SkShadowPaintFilterCanvas.cpp',
+        '<(skia_src_path)/utils/SkShadowPaintFilterCanvas.h',
         '<(skia_src_path)/utils/SkTextBox.cpp',
         '<(skia_src_path)/utils/SkTextureCompressor.cpp',
         '<(skia_src_path)/utils/SkTextureCompressor.h',
diff --git a/samplecode/SampleShadowing.cpp b/samplecode/SampleShadowing.cpp
new file mode 100644
index 0000000..3907db3
--- /dev/null
+++ b/samplecode/SampleShadowing.cpp
@@ -0,0 +1,307 @@
+/*
+ * Copyright 2016 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "SampleCode.h"
+#include "SkPictureRecorder.h"
+#include "SkShadowPaintFilterCanvas.h"
+#include "SkShadowShader.h"
+#include "SkSurface.h"
+
+#ifdef SK_EXPERIMENTAL_SHADOWING
+
+static sk_sp<SkShader> make_shadow_shader(sk_sp<SkImage> povDepth,
+                                          sk_sp<SkImage> diffuse,
+                                          sk_sp<SkLights> lights) {
+
+    sk_sp<SkShader> povDepthShader = povDepth->makeShader(SkShader::kClamp_TileMode,
+                                                          SkShader::kClamp_TileMode);
+
+    sk_sp<SkShader> diffuseShader = diffuse->makeShader(SkShader::kClamp_TileMode,
+                                                        SkShader::kClamp_TileMode);
+
+    return SkShadowShader::Make(std::move(povDepthShader),
+                                std::move(diffuseShader),
+                                std::move(lights),
+                                diffuse->width(), diffuse->height());
+}
+
+class ShadowingView : public SampleView {
+public:
+    ShadowingView() {
+
+        this->setBGColor(0xFFCCCCCC);
+        SkLights::Builder builder;
+        builder.add(SkLights::Light(SkColor3f::Make(0.2f, 0.3f, 0.4f),
+                                    SkVector3::Make(0.27f, 0.07f, 1.0f)));
+        builder.add(SkLights::Light(SkColor3f::Make(0.4f, 0.3f, 0.2f),
+                                    SkVector3::Make(0.03f, 0.27f, 1.0f)));
+        builder.add(SkLights::Light(SkColor3f::Make(0.4f, 0.4f, 0.4f)));
+        fLights = builder.finish();
+
+        fTestRects[0].fColor = 0xFFEE8888;
+        fTestRects[0].fDepth = 80;
+        fTestRects[0].fGeometry = SkRect::MakeLTRB(200,150,350,300);
+
+        fTestRects[1].fColor = 0xFF88EE88;
+        fTestRects[1].fDepth = 160;
+        fTestRects[1].fGeometry = SkRect::MakeLTRB(150,200,300,350);
+
+        fTestRects[2].fColor = 0xFF8888EE;
+        fTestRects[2].fDepth = 240;
+        fTestRects[2].fGeometry = SkRect::MakeLTRB(100,100,250,250);
+
+        fSceneChanged = true;
+        fLightsChanged = true;
+
+        fSelectedRect = -1;
+        fMoveLight = false;
+    }
+
+protected:
+    bool onQuery(SkEvent *evt) override {
+        if (SampleCode::TitleQ(*evt)) {
+            SampleCode::TitleR(evt, "shadowing");
+            return true;
+        }
+
+        SkUnichar uni;
+        if (SampleCode::CharQ(*evt, &uni)) {
+            switch (uni) {
+                case 'L':
+                    fMoveLight = !fMoveLight;
+                    break;
+                default:
+                    break;
+            }
+        }
+        return this->INHERITED::onQuery(evt);
+    }
+
+    sk_sp<SkPicture> makeTestPicture(int width, int height) {
+        SkPictureRecorder recorder;
+
+        // LONG RANGE TODO: eventually add SkBBHFactory (bounding box factory)
+        SkCanvas* canvas = recorder.beginRecording(SkRect::MakeIWH(width, height));
+
+        SkASSERT(canvas->getTotalMatrix().isIdentity());
+        SkPaint paint;
+        paint.setColor(SK_ColorGRAY);
+
+        // LONG RANGE TODO: tag occluders
+        // LONG RANGE TODO: track number of IDs we need (hopefully less than 256)
+        //                  and determinate the mapping from z to id
+
+        // universal receiver, "ground"
+        canvas->drawRect(SkRect::MakeIWH(width, height), paint);
+
+        for (int i = 0; i < kNumTestRects; i++) {
+            paint.setColor(fTestRects[i].fColor);
+            if (i == 0) {
+                canvas->translateZ(fTestRects[0].fDepth);
+            } else {
+                canvas->translateZ(fTestRects[i].fDepth - fTestRects[i-1].fDepth);
+            }
+            canvas->drawRect(fTestRects[i].fGeometry, paint);
+        }
+
+        return recorder.finishRecordingAsPicture();
+    }
+
+    void updateDepthMaps(SkCanvas *canvas) {
+        for (int i = 0; i < fLights->numLights(); ++i) {
+            // skip over ambient lights; they don't cast shadows
+            if (SkLights::Light::kAmbient_LightType == fLights->light(i).type()) {
+                continue;
+            }
+
+            // TODO: maybe add a kDepth_8_SkColorType when vertices have depth
+            // assume max depth is 255.
+            // TODO: find actual max depth of picture
+            SkISize shMapSize = SkShadowPaintFilterCanvas::
+                                ComputeDepthMapSize(fLights->light(i), 255, kWidth, kHeight);
+
+            SkImageInfo info = SkImageInfo::Make(shMapSize.fWidth, shMapSize.fHeight,
+                                                 kBGRA_8888_SkColorType,
+                                                 kOpaque_SkAlphaType);
+
+            // Create a new surface (that matches the backend of canvas)
+            // for each shadow map
+            sk_sp<SkSurface> surf(canvas->makeSurface(info));
+
+            // Wrap another SPFCanvas around the surface
+            sk_sp<SkShadowPaintFilterCanvas> depthMapCanvas =
+                    sk_make_sp<SkShadowPaintFilterCanvas>(surf->getCanvas());
+
+            // set the depth map canvas to have the light we're drawing.
+            SkLights::Builder builder;
+            builder.add(fLights->light(i));
+            sk_sp<SkLights> curLight = builder.finish();
+
+            depthMapCanvas->setLights(std::move(curLight));
+            depthMapCanvas->drawPicture(fPicture);
+
+            fLights->light(i).setShadowMap(surf->makeImageSnapshot());
+        }
+    }
+
+    void updatePovDepthMap(SkCanvas* canvas) {
+        // TODO: pass the depth to the shader in vertices, or uniforms
+        //       so we don't have to render depth and color separately
+
+        SkLights::Builder builder;
+        builder.add(SkLights::Light(SkColor3f::Make(1.0f, 1.0f, 1.0f),
+                                    SkVector3::Make(0.0f, 0.0f, 1.0f)));
+        sk_sp<SkLights> povLight = builder.finish();
+
+        SkImageInfo info = SkImageInfo::Make(kWidth, kHeight,
+                                             kBGRA_8888_SkColorType,
+                                             kOpaque_SkAlphaType);
+
+        // Create a new surface (that matches the backend of canvas)
+        // to create the povDepthMap
+        sk_sp<SkSurface> surf(canvas->makeSurface(info));
+
+        // Wrap another SPFCanvas around the surface
+        sk_sp<SkShadowPaintFilterCanvas> depthMapCanvas =
+                sk_make_sp<SkShadowPaintFilterCanvas>(surf->getCanvas());
+
+        // set the depth map canvas to have the light as the user's POV
+        depthMapCanvas->setLights(std::move(povLight));
+
+        depthMapCanvas->drawPicture(fPicture);
+
+        fPovDepthMap = surf->makeImageSnapshot();
+    }
+
+    void updateDiffuseMap(SkCanvas* canvas) {
+        SkImageInfo info = SkImageInfo::Make(kWidth, kHeight,
+                                             kBGRA_8888_SkColorType,
+                                             kOpaque_SkAlphaType);
+
+        sk_sp<SkSurface> surf(canvas->makeSurface(info));
+        surf->getCanvas()->drawPicture(fPicture);
+
+        fDiffuseMap = surf->makeImageSnapshot();
+    }
+
+    void onDrawContent(SkCanvas *canvas) override {
+        if (fSceneChanged || !fPovDepthMap) {
+            fPicture = this->makeTestPicture(kWidth, kHeight);
+            this->updateDepthMaps(canvas);
+            this->updatePovDepthMap(canvas);
+            this->updateDiffuseMap(canvas);
+        }
+
+        if (fLightsChanged) {
+            this->updateDepthMaps(canvas);
+        }
+
+        if (fSceneChanged || fLightsChanged || !fShadowShader) {
+            fShadowShader = make_shadow_shader(fPovDepthMap, fDiffuseMap, fLights);
+        }
+
+        SkPaint paint;
+        paint.setShader(fShadowShader);
+
+        canvas->drawRect(SkRect::MakeIWH(kWidth, kHeight), paint);
+    }
+
+    SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned modi) override {
+        return new SkView::Click(this);
+    }
+
+    bool onClick(Click *click) override {
+        SkScalar x = click->fCurr.fX;
+        SkScalar y = click->fCurr.fY;
+
+        SkScalar dx = x - click->fPrev.fX;
+        SkScalar dy = y - click->fPrev.fY;
+
+        if (fMoveLight) {
+            if (dx != 0 || dy != 0) {
+                float recipX = 1.0f / kWidth;
+                float recipY = 1.0f / kHeight;
+
+                SkLights::Builder builder;
+                builder.add(SkLights::Light(SkColor3f::Make(0.2f, 0.3f, 0.4f),
+                                            SkVector3::Make(0.12f + (200.0f - x) * recipX,
+                                                            -0.08f + (200.0f - y) * recipY,
+                                                            1.0f)));
+                builder.add(SkLights::Light(SkColor3f::Make(0.4f, 0.3f, 0.2f),
+                                            SkVector3::Make(-0.12f + (200.0f - x) * recipX,
+                                                            0.12f + (200.0f - y) * recipY,
+                                                            1.0f)));
+                builder.add(SkLights::Light(SkColor3f::Make(0.4f, 0.4f, 0.4f)));
+                fLights = builder.finish();
+
+                fLightsChanged = true;
+                this->inval(nullptr);
+            }
+            return true;
+        }
+
+        if (click->fState == Click::State::kUp_State) {
+            fSelectedRect = -1;
+            return true;
+        }
+
+        if (fSelectedRect > -1) {
+            fTestRects[fSelectedRect].fGeometry.offset(dx, dy);
+
+            fSceneChanged = true;
+            this->inval(nullptr);
+            return true;
+        }
+
+        // assume last elements are highest
+        for (int i = kNumTestRects - 1; i >= 0; i--) {
+            if (fTestRects[i].fGeometry.contains(SkRect::MakeXYWH(x, y, 1, 1))) {
+                fSelectedRect = i;
+                fTestRects[i].fGeometry.offset(dx, dy);
+
+                fSceneChanged = true;
+                this->inval(nullptr);
+                break;
+            }
+        }
+
+        return true;
+    }
+
+private:
+    static constexpr int kNumTestRects = 3;
+
+    static const int kWidth = 400;
+    static const int kHeight = 400;
+
+    struct {
+        SkRect  fGeometry;
+        int     fDepth;
+        SkColor fColor;
+    } fTestRects[kNumTestRects];
+
+    int fSelectedRect;
+    bool fMoveLight;
+
+    sk_sp<SkImage>   fPovDepthMap;
+    sk_sp<SkImage>   fDiffuseMap;
+    sk_sp<SkPicture> fPicture;
+    sk_sp<SkShader>  fShadowShader;
+
+    bool fSceneChanged;
+    bool fLightsChanged;
+
+    sk_sp<SkLights> fLights;
+
+    typedef SampleView INHERITED;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+static SkView* MyFactory() { return new ShadowingView; }
+static SkViewRegister reg(MyFactory);
+
+#endif
diff --git a/src/core/SkShadowShader.cpp b/src/core/SkShadowShader.cpp
index c5a99e9..5fc992a 100644
--- a/src/core/SkShadowShader.cpp
+++ b/src/core/SkShadowShader.cpp
@@ -14,7 +14,6 @@
 ////////////////////////////////////////////////////////////////////////////
 #ifdef SK_EXPERIMENTAL_SHADOWING
 
-#define SK_MAX_NON_AMBIENT_LIGHTS 4
 
 /** \class SkShadowShaderImpl
     This subclass of shader applies shadowing
@@ -116,12 +115,12 @@
         for (int i = 0; i < lights->numLights(); ++i) {
             if (SkLights::Light::kAmbient_LightType == lights->light(i).type()) {
                 fAmbientColor += lights->light(i).color();
-            } else if (fNumDirLights < SK_MAX_NON_AMBIENT_LIGHTS){
+            } else if (fNumDirLights < SkShadowShader::kMaxNonAmbientLights) {
                 fLightColor[fNumDirLights] = lights->light(i).color();
                 fLightDir[fNumDirLights] = lights->light(i).dir();
-                SkImage_Base* shadowMap = ((SkImage_Base*)lights->light(i).getShadowMap().get());
+                SkImage_Base* shadowMap = ((SkImage_Base*)lights->light(i).getShadowMap());
 
-                // this sk_sp gets deleted when the ShadowFP is destroyed, and frees the GrTexture*
+                // gets deleted when the ShadowFP is destroyed, and frees the GrTexture*
                 fTexture[fNumDirLights] = sk_sp<GrTexture>(shadowMap->asTextureRef(context,
                                                            GrTextureParams::ClampNoFilter(),
                                                            SkSourceGammaTreatment::kIgnore));
@@ -154,13 +153,15 @@
 
             // add uniforms
             int32_t numLights = args.fFp.cast<ShadowFP>().fNumDirLights;
-            SkASSERT(numLights <= SK_MAX_NON_AMBIENT_LIGHTS);
+            SkASSERT(numLights <= SkShadowShader::kMaxNonAmbientLights);
 
-            const char* lightDirUniName[SK_MAX_NON_AMBIENT_LIGHTS] = {nullptr};
-            const char* lightColorUniName[SK_MAX_NON_AMBIENT_LIGHTS] = {nullptr};
+            const char* lightDirUniName[SkShadowShader::kMaxNonAmbientLights] = {nullptr};
+            const char* lightColorUniName[SkShadowShader::kMaxNonAmbientLights] = {nullptr};
 
-            const char* depthMapWidthUniName[SK_MAX_NON_AMBIENT_LIGHTS] = {nullptr};
-            const char* depthMapHeightUniName[SK_MAX_NON_AMBIENT_LIGHTS] = {nullptr};
+            const char* depthMapWidthUniName[SkShadowShader::kMaxNonAmbientLights]
+                    = {nullptr};
+            const char* depthMapHeightUniName[SkShadowShader::kMaxNonAmbientLights]
+                    = {nullptr};
 
             SkString lightDirUniNameBase("lightDir");
             SkString lightColorUniNameBase("lightColor");
@@ -222,7 +223,7 @@
             SkString diffuseColor("inDiffuseColor");
             this->emitChild(1, nullptr, &diffuseColor, args);
 
-            SkString depthMaps[SK_MAX_NON_AMBIENT_LIGHTS];
+            SkString depthMaps[SkShadowShader::kMaxNonAmbientLights];
 
             for (int i = 0; i < numLights; i++) {
                 SkString povCoord("povCoord");
@@ -354,15 +355,21 @@
         }
 
     private:
-        SkVector3 fLightDir[SK_MAX_NON_AMBIENT_LIGHTS];
-        GrGLSLProgramDataManager::UniformHandle fLightDirUni[SK_MAX_NON_AMBIENT_LIGHTS];
-        SkColor3f fLightColor[SK_MAX_NON_AMBIENT_LIGHTS];
-        GrGLSLProgramDataManager::UniformHandle fLightColorUni[SK_MAX_NON_AMBIENT_LIGHTS];
+        SkVector3 fLightDir[SkShadowShader::kMaxNonAmbientLights];
+        GrGLSLProgramDataManager::UniformHandle
+                fLightDirUni[SkShadowShader::kMaxNonAmbientLights];
 
-        int fDepthMapWidth[SK_MAX_NON_AMBIENT_LIGHTS];
-        GrGLSLProgramDataManager::UniformHandle fDepthMapWidthUni[SK_MAX_NON_AMBIENT_LIGHTS];
-        int fDepthMapHeight[SK_MAX_NON_AMBIENT_LIGHTS];
-        GrGLSLProgramDataManager::UniformHandle fDepthMapHeightUni[SK_MAX_NON_AMBIENT_LIGHTS];
+        SkColor3f fLightColor[SkShadowShader::kMaxNonAmbientLights];
+        GrGLSLProgramDataManager::UniformHandle
+                fLightColorUni[SkShadowShader::kMaxNonAmbientLights];
+
+        int fDepthMapWidth[SkShadowShader::kMaxNonAmbientLights];
+        GrGLSLProgramDataManager::UniformHandle
+                fDepthMapWidthUni[SkShadowShader::kMaxNonAmbientLights];
+
+        int fDepthMapHeight[SkShadowShader::kMaxNonAmbientLights];
+        GrGLSLProgramDataManager::UniformHandle
+                fDepthMapHeightUni[SkShadowShader::kMaxNonAmbientLights];
 
         int fWidth;
         GrGLSLProgramDataManager::UniformHandle fWidthUni;
@@ -436,13 +443,13 @@
 
     int              fNumDirLights;
 
-    SkVector3        fLightDir[SK_MAX_NON_AMBIENT_LIGHTS];
-    SkColor3f        fLightColor[SK_MAX_NON_AMBIENT_LIGHTS];
-    GrTextureAccess  fDepthMapAccess[SK_MAX_NON_AMBIENT_LIGHTS];
-    sk_sp<GrTexture> fTexture[SK_MAX_NON_AMBIENT_LIGHTS];
+    SkVector3        fLightDir[SkShadowShader::kMaxNonAmbientLights];
+    SkColor3f        fLightColor[SkShadowShader::kMaxNonAmbientLights];
+    GrTextureAccess  fDepthMapAccess[SkShadowShader::kMaxNonAmbientLights];
+    sk_sp<GrTexture> fTexture[SkShadowShader::kMaxNonAmbientLights];
 
-    int              fDepthMapWidth[SK_MAX_NON_AMBIENT_LIGHTS];
-    int              fDepthMapHeight[SK_MAX_NON_AMBIENT_LIGHTS];
+    int              fDepthMapWidth[SkShadowShader::kMaxNonAmbientLights];
+    int              fDepthMapHeight[SkShadowShader::kMaxNonAmbientLights];
 
     int              fHeight;
     int              fWidth;
@@ -647,7 +654,7 @@
             buf.writeScalarArray(&light.dir().fX, 3);
         }
 
-        buf.writeImage(light.getShadowMap().get());
+        buf.writeImage(light.getShadowMap());
     }
 
     buf.writeInt(fDiffuseWidth);
diff --git a/src/core/SkShadowShader.h b/src/core/SkShadowShader.h
index 7cbcbca..163d58a 100644
--- a/src/core/SkShadowShader.h
+++ b/src/core/SkShadowShader.h
@@ -25,6 +25,10 @@
                                 sk_sp<SkLights> lights,
                                 int diffuseWidth, int diffuseHeight);
 
+    // The shadow shader supports any number of ambient lights, but only
+    // 4 non-ambient lights (currently just refers to directional lights).
+    static constexpr int kMaxNonAmbientLights = 4;
+
     SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP()
 };
 
diff --git a/src/utils/SkShadowPaintFilterCanvas.cpp b/src/utils/SkShadowPaintFilterCanvas.cpp
new file mode 100644
index 0000000..31b7661
--- /dev/null
+++ b/src/utils/SkShadowPaintFilterCanvas.cpp
@@ -0,0 +1,221 @@
+/*
+ * Copyright 2016 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "SkPathEffect.h"
+#include "SkShadowPaintFilterCanvas.h"
+
+#ifdef SK_EXPERIMENTAL_SHADOWING
+
+SkShadowPaintFilterCanvas::SkShadowPaintFilterCanvas(SkCanvas *canvas)
+        : SkPaintFilterCanvas(canvas) { }
+
+// TODO use a shader instead
+bool SkShadowPaintFilterCanvas::onFilter(SkTCopyOnFirstWrite<SkPaint>* paint, Type type) const {
+    if (*paint) {
+        int z = this->getZ();
+        SkASSERT(z <= 0xFF && z >= 0x00);
+
+        SkPaint newPaint;
+        newPaint.setPathEffect(sk_ref_sp<SkPathEffect>((*paint)->getPathEffect()));
+
+        SkColor color = 0xFF000000; // init color to opaque black
+        color |= z; // Put the index into the blue component
+        newPaint.setColor(color);
+
+        *paint->writable() = newPaint;
+    }
+
+    return true;
+}
+
+SkISize SkShadowPaintFilterCanvas::ComputeDepthMapSize(const SkLights::Light& light, int maxDepth,
+                                                       int width, int height) {
+    SkASSERT(light.type() != SkLights::Light::kAmbient_LightType);
+    int dMapWidth = SkMin32(maxDepth * fabs(light.dir().fX) + width,
+                            width * 2);
+    int dMapHeight = SkMin32(maxDepth * fabs(light.dir().fY) + height,
+                             height * 2);
+    return SkISize::Make(dMapWidth, dMapHeight);
+}
+
+
+void SkShadowPaintFilterCanvas::onDrawPicture(const SkPicture *picture, const SkMatrix *matrix,
+                                              const SkPaint *paint) {
+    SkTCopyOnFirstWrite<SkPaint> filteredPaint(paint);
+    if (this->onFilter(&filteredPaint, kPicture_Type)) {
+        SkCanvas::onDrawPicture(picture, matrix, filteredPaint);
+    }
+}
+
+void SkShadowPaintFilterCanvas::updateMatrix() {
+    this->save();
+
+    //  It is up to the user to set the 0th light in fLights to
+    //  the light the want to render the depth map with.
+    if (this->fLights->light(0).type() != SkLights::Light::kAmbient_LightType) {
+        const SkVector3& lightDir = this->fLights->light(0).dir();
+        SkScalar x = lightDir.fX * this->getZ();
+        SkScalar y = lightDir.fY * this->getZ();
+
+        this->translate(x, y);
+    }
+}
+
+void SkShadowPaintFilterCanvas::onDrawPaint(const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawPaint(paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawPoints(PointMode mode, size_t count, const SkPoint pts[],
+                                             const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawPoints(mode, count, pts, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawRect(const SkRect &rect, const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawRect(rect, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawRRect(const SkRRect &rrect, const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawRRect(rrect, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawDRRect(const SkRRect &outer, const SkRRect &inner,
+                  const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawDRRect(outer, inner, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawOval(const SkRect &rect, const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawOval(rect, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawPath(const SkPath &path, const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawPath(path, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawBitmap(const SkBitmap &bm, SkScalar left, SkScalar top,
+                                             const SkPaint *paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawBitmap(bm, left, top, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawBitmapRect(const SkBitmap &bm, const SkRect *src,
+                                                 const SkRect &dst, const SkPaint *paint,
+                                                 SrcRectConstraint constraint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawBitmapRect(bm, src, dst, paint, constraint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawBitmapNine(const SkBitmap &bm, const SkIRect &center,
+                                                 const SkRect &dst, const SkPaint *paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawBitmapNine(bm, center, dst, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawImage(const SkImage *image, SkScalar left,
+                                            SkScalar top, const SkPaint *paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawImage(image, left, top, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawImageRect(const SkImage *image, const SkRect *src,
+                                                const SkRect &dst, const SkPaint *paint,
+                                                SrcRectConstraint constraint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawImageRect(image, src, dst, paint, constraint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawImageNine(const SkImage *image, const SkIRect &center,
+                                                const SkRect &dst, const SkPaint *paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawImageNine(image, center, dst, paint);
+    this->restore();
+}
+
+
+void SkShadowPaintFilterCanvas::onDrawVertices(VertexMode vmode, int vertexCount,
+                                               const SkPoint vertices[], const SkPoint texs[],
+                                               const SkColor colors[], SkXfermode *xmode,
+                                               const uint16_t indices[], int indexCount,
+                                               const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawVertices(vmode, vertexCount, vertices, texs, colors,
+                                    xmode, indices, indexCount, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawPatch(const SkPoint cubics[], const SkColor colors[],
+                                            const SkPoint texCoords[], SkXfermode *xmode,
+                                            const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawPatch(cubics, colors, texCoords, xmode, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawText(const void *text, size_t byteLength, SkScalar x,
+                                           SkScalar y, const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawText(text, byteLength, x, y, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawPosText(const void *text, size_t byteLength,
+                                              const SkPoint pos[], const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawPosText(text, byteLength, pos, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawPosTextH(const void *text, size_t byteLength,
+                                               const SkScalar xpos[],
+                                               SkScalar constY, const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawPosTextH(text, byteLength, xpos, constY, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawTextOnPath(const void *text, size_t byteLength,
+                                                 const SkPath &path, const SkMatrix *matrix,
+                                                 const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawTextOnPath(text, byteLength, path, matrix, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawTextRSXform(const void *text, size_t byteLength,
+                                                  const SkRSXform xform[], const SkRect *cull,
+                                                  const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawTextRSXform(text, byteLength, xform, cull, paint);
+    this->restore();
+}
+
+void SkShadowPaintFilterCanvas::onDrawTextBlob(const SkTextBlob *blob, SkScalar x, SkScalar y,
+                                               const SkPaint &paint) {
+    this->updateMatrix();
+    this->INHERITED::onDrawTextBlob(blob, x, y, paint);
+    this->restore();
+}
+
+#endif
diff --git a/src/utils/SkShadowPaintFilterCanvas.h b/src/utils/SkShadowPaintFilterCanvas.h
new file mode 100644
index 0000000..ae449d6
--- /dev/null
+++ b/src/utils/SkShadowPaintFilterCanvas.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2016 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkShadowPaintFilterCanvas_DEFINED
+#define SkShadowPaintFilterCanvas_DEFINED
+
+#include "SkPaintFilterCanvas.h"
+
+#ifdef SK_EXPERIMENTAL_SHADOWING
+
+/** \class SkShadowPaintFilterCanvas
+ *
+ *  A utility proxy class for implementing shadow maps.
+ *
+ *  We override the onFilter method to draw depths into the canvas
+ *  depending on the current draw depth of the canvas, throwing out
+ *  the actual draw color.
+ *
+ *  Note that we can only do this for one light at a time!
+ *  It is up to the user to set the 0th light in fLights to
+ *  the light the want to render the depth map with.
+ */
+class SkShadowPaintFilterCanvas : public SkPaintFilterCanvas {
+public:
+
+    SkShadowPaintFilterCanvas(SkCanvas *canvas);
+
+    // TODO use a shader instead
+    bool onFilter(SkTCopyOnFirstWrite<SkPaint>* paint, Type type) const override;
+
+    static SkISize ComputeDepthMapSize(const SkLights::Light& light, int maxDepth,
+                                       int width, int height);
+
+protected:
+    void onDrawPicture(const SkPicture *picture, const SkMatrix *matrix,
+                       const SkPaint *paint) override;
+
+    void updateMatrix();
+
+    void onDrawPaint(const SkPaint &paint) override;
+
+    void onDrawPoints(PointMode mode, size_t count, const SkPoint pts[],
+                      const SkPaint &paint) override;
+
+    void onDrawRect(const SkRect &rect, const SkPaint &paint) override;
+
+    void onDrawRRect(const SkRRect &rrect, const SkPaint &paint) override;
+
+    void onDrawDRRect(const SkRRect &outer, const SkRRect &inner,
+                      const SkPaint &paint) override;
+
+    void onDrawOval(const SkRect &rect, const SkPaint &paint) override;
+
+    void onDrawPath(const SkPath &path, const SkPaint &paint) override;
+
+    void onDrawBitmap(const SkBitmap &bm, SkScalar left, SkScalar top,
+                      const SkPaint *paint) override;
+
+    void onDrawBitmapRect(const SkBitmap &bm, const SkRect *src, const SkRect &dst,
+                          const SkPaint *paint, SrcRectConstraint constraint) override;
+
+    void onDrawBitmapNine(const SkBitmap &bm, const SkIRect &center,
+                          const SkRect &dst, const SkPaint *paint) override;
+
+    void onDrawImage(const SkImage *image, SkScalar left, SkScalar top,
+                     const SkPaint *paint) override;
+
+    void onDrawImageRect(const SkImage *image, const SkRect *src,
+                         const SkRect &dst, const SkPaint *paint,
+                         SrcRectConstraint constraint) override;
+
+    void onDrawImageNine(const SkImage *image, const SkIRect &center,
+                         const SkRect &dst, const SkPaint *paint) override;
+
+    void onDrawVertices(VertexMode vmode, int vertexCount,
+                        const SkPoint vertices[], const SkPoint texs[],
+                        const SkColor colors[], SkXfermode *xmode,
+                        const uint16_t indices[], int indexCount,
+                        const SkPaint &paint) override;
+
+    void onDrawPatch(const SkPoint cubics[], const SkColor colors[],
+                     const SkPoint texCoords[], SkXfermode *xmode,
+                     const SkPaint &paint) override;
+
+    void onDrawText(const void *text, size_t byteLength, SkScalar x, SkScalar y,
+                    const SkPaint &paint) override;
+
+    void onDrawPosText(const void *text, size_t byteLength, const SkPoint pos[],
+                       const SkPaint &paint) override;
+
+    void onDrawPosTextH(const void *text, size_t byteLength, const SkScalar xpos[],
+                        SkScalar constY, const SkPaint &paint) override;
+
+    void onDrawTextOnPath(const void *text, size_t byteLength, const SkPath &path,
+                          const SkMatrix *matrix, const SkPaint &paint) override;
+
+    void onDrawTextRSXform(const void *text, size_t byteLength,
+                           const SkRSXform xform[], const SkRect *cull,
+                           const SkPaint &paint) override;
+
+    void onDrawTextBlob(const SkTextBlob *blob, SkScalar x,
+                        SkScalar y, const SkPaint &paint) override;
+private:
+    typedef SkPaintFilterCanvas INHERITED;
+};
+
+
+#endif
+#endif