Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(99)

Side by Side Diff: src/core/SkShadowShader.cpp

Issue 2118553002: adding new GM to demostrate new shadows (Closed) Base URL: https://skia.googlesource.com/skia@master
Patch Set: made req changes Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« gm/shadowmaps.cpp ('K') | « src/core/SkShadowShader.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "SkLights.h"
9 #include "SkReadBuffer.h"
10 #include "SkShadowShader.h"
11 #include "SkPoint3.h"
12
13 ////////////////////////////////////////////////////////////////////////////
14 #define SK_MAX_NON_AMBIENT_LIGHTS 4
15
16 /** \class SkShadowShaderImpl
17 This subclass of shader applies shadowing
18 */
19 class SkShadowShaderImpl : public SkShader {
20 public:
21 /** Create a new shadowing shader that shadows
22 @param to do to do
23 */
24 SkShadowShaderImpl(sk_sp<SkShader> povDepthShader,
25 sk_sp<SkShader> diffuseShader,
26 sk_sp<SkLights> lights)
27 : povDepthShader(std::move(povDepthShader))
28 , diffuseShader(std::move(diffuseShader))
29 , fLights(std::move(lights)) { }
30
31 bool isOpaque() const override;
32
33 #if SK_SUPPORT_GPU
34 sk_sp<GrFragmentProcessor> asFragmentProcessor(const AsFPArgs&) const overri de;
35 #endif
36
37 class ShadowShaderContext : public SkShader::Context {
38 public:
39 // The context takes ownership of the states. It will call their destruc tors
40 // but will NOT free the memory.
41 ShadowShaderContext(const SkShadowShaderImpl&, const ContextRec&,
42 SkShader::Context* povDepthContext,
43 SkShader::Context* diffuseContext,
44 void* heapAllocated);
45
46 ~ShadowShaderContext() override;
47
48 void shadeSpan(int x, int y, SkPMColor[], int count) override;
49
50 uint32_t getFlags() const override { return fFlags; }
51
52 private:
53 SkShader::Context* fPovDepthContext;
54 SkShader::Context* fDiffuseContext;
55 uint32_t fFlags;
56
57 void* fHeapAllocated;
58
59 typedef SkShader::Context INHERITED;
60 };
61
62 SK_TO_STRING_OVERRIDE()
63 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkShadowShaderImpl)
64
65 protected:
66 void flatten(SkWriteBuffer&) const override;
67 size_t onContextSize(const ContextRec&) const override;
68 Context* onCreateContext(const ContextRec&, void*) const override;
69
70 private:
71 sk_sp<SkShader> povDepthShader;
72 sk_sp<SkShader> diffuseShader;
73 sk_sp<SkLights> fLights;
74
75 friend class SkShadowShader;
76
77 typedef SkShader INHERITED;
78 };
79
80 ////////////////////////////////////////////////////////////////////////////
81
82 #if SK_SUPPORT_GPU
83
84 #include "GrCoordTransform.h"
85 #include "GrFragmentProcessor.h"
86 #include "GrInvariantOutput.h"
87 #include "glsl/GrGLSLFragmentProcessor.h"
88 #include "glsl/GrGLSLFragmentShaderBuilder.h"
89 #include "SkGr.h"
90 #include "SkGrPriv.h"
91 #include "SkSpecialImage.h"
92 #include "SkImage_Base.h"
93 #include "GrContext.h"
94
95 class ShadowFP : public GrFragmentProcessor {
96 public:
97 ShadowFP(sk_sp<GrFragmentProcessor> povDepth,
98 sk_sp<GrFragmentProcessor> diffuse,
99 sk_sp<SkLights> lights,
100 GrContext* context) {
101
102 // fuse all ambient lights into a single one
103 fAmbientColor.set(0.0f, 0.0f, 0.0f);
104
105 fNumDirLights = 0; // refers to directional lights.
106 for (int i = 0; i < lights->numLights(); ++i) {
107 if (SkLights::Light::kAmbient_LightType == lights->light(i).type()) {
108 fAmbientColor += lights->light(i).color();
109 } else if (fNumDirLights < SK_MAX_NON_AMBIENT_LIGHTS){
110 fLightColor[fNumDirLights] = lights->light(i).color();
111 fLightDir[fNumDirLights] = lights->light(i).dir();
112 SkImage_Base* shadowMap = ((SkImage_Base*)lights->light(i).getSh adowMap().get());
113
114 // this sk_sp gets deleted when the ShadowFP is destroyed, and f rees the GrTexture*
115 fTexture[fNumDirLights] = sk_sp<GrTexture>(shadowMap->asTextureR ef(context,
116 GrTextureParams::Clam pNoFilter(),
117 SkSourceGammaTreatmen t::kIgnore));
118 fDepthMapAccess[fNumDirLights].reset(fTexture[fNumDirLights].get ());
119 this->addTextureAccess(&fDepthMapAccess[fNumDirLights]);
120
121 fNumDirLights++;
122 }
123 }
124
125 this->registerChildProcessor(std::move(povDepth));
126 this->registerChildProcessor(std::move(diffuse));
127 this->initClassID<ShadowFP>();
128 }
129
130 class GLSLShadowFP : public GrGLSLFragmentProcessor {
131 public:
132 GLSLShadowFP() { }
133
134 void emitCode(EmitArgs& args) override {
135
136 GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
137 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
138
139 // add uniforms
140 int32_t numLights = args.fFp.cast<ShadowFP>().fNumDirLights;
robertphillips 2016/07/29 17:58:12 Maybe assert here that numLights <= SK_MAX_NON_AMB
vjiaoblack 2016/07/29 18:09:13 Done.
141
142 const char* lightDirUniName[SK_MAX_NON_AMBIENT_LIGHTS] = {nullptr};
143 const char* lightColorUniName[SK_MAX_NON_AMBIENT_LIGHTS] = {nullptr} ;
144
145 for (int i = 0; i < numLights; i++) {
146 fLightDirUni[i] = uniformHandler->addUniform(kFragment_GrShaderF lag,
147 kVec3f_GrSLType,
148 kDefault_GrSLPrecis ion,
149 "LightDir" + (i+1),
150 &lightDirUniName[i] );
151 fLightColorUni[i] = uniformHandler->addUniform(kFragment_GrShade rFlag,
152 kVec3f_GrSLType,
153 kDefault_GrSLPrec ision,
154 "LightColor" + (i +1),
155 &lightColorUniNam e[i]);
156 }
157
158 SkString povDepth("povDepth");
159 this->emitChild(0, nullptr, &povDepth, args);
160
161 SkString diffuseColor("inDiffuseColor");
162 this->emitChild(1, nullptr, &diffuseColor, args);
163
164 SkString depthMaps[SK_MAX_NON_AMBIENT_LIGHTS];
165
166 for (int i = 0; i < numLights; i++) {
167 SkString povCoord("povCoord");
168 povCoord.appendf("%d", i);
169
170 // vMatrixCoord_0_1_Stage0 is the texture sampler coordinates.
171 // povDepth.b * 255 scales it to 0 - 255, bringing it to world s pace,
172 // and the / 400 brings it back to a sampler coordinate, 0 - 1
173 // The 400 comes from the shadowmaps GM.
174 // TODO use real shadowmaps size
175 SkString offset("lol");
176 offset.appendf("%d", i);
177
178 fragBuilder->codeAppendf("vec2 %s = (vec2(%s) * povDepth.b * 255 / 400);",
179 offset.c_str(), lightDirUniName[i]);
180
181
182 fragBuilder->codeAppendf("vec2 %s = vec2(vMatrixCoord_0_1_Stage0 .x, "
183 "vMatrixCoord_0_1_Stage0 .y) + "
184 "vec2(%s.x, 0 - %s.y);",
185 povCoord.c_str(), offset.c_str(), offse t.c_str());
186
187 fragBuilder->appendTextureLookup(&depthMaps[i], args.fTexSampler s[i],
188 povCoord.c_str(),
189 kVec2f_GrSLType);
190 }
191
192 const char* ambientColorUniName = nullptr;
193 fAmbientColorUni = uniformHandler->addUniform(kFragment_GrShaderFlag ,
194 kVec3f_GrSLType, kDefa ult_GrSLPrecision,
195 "AmbientColor", &ambie ntColorUniName);
196
197 fragBuilder->codeAppendf("vec4 resultDiffuseColor = %s;", diffuseCol or.c_str());
198
199 // diffColor * (ambientLightTot + foreachDirLight(lightColor * (N . L)))
200 SkString totalLightColor("totalLightColor");
201 fragBuilder->codeAppendf("vec3 %s = vec3(0);", totalLightColor.c_str ());
202
203 for (int i = 0; i < numLights ; i++) {
204 fragBuilder->codeAppendf("if (%s.b >= %s.b) {",
205 povDepth.c_str(), depthMaps[i].c_str()) ;
206 // dot(vec3(0,0,1), %s) == %s.z * %s
207 fragBuilder->codeAppendf("%s += %s.z * %s;",
208 totalLightColor.c_str(),
209 lightDirUniName[i],
210 lightColorUniName[i]);
211 fragBuilder->codeAppendf("}");
212 }
213
214 fragBuilder->codeAppendf("%s += %s;",
215 totalLightColor.c_str(),
216 ambientColorUniName);
217
218 fragBuilder->codeAppendf("resultDiffuseColor *= vec4(%s, 1);",
219 totalLightColor.c_str());
220
221 fragBuilder->codeAppendf("%s = resultDiffuseColor;", args.fOutputCol or);
222 }
223
224 static void GenKey(const GrProcessor& proc, const GrGLSLCaps&,
225 GrProcessorKeyBuilder* b) {
226 const ShadowFP& shadowFP = proc.cast<ShadowFP>();
227 b->add32(shadowFP.fNumDirLights);
228 }
229
230 protected:
231 void onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) override {
232 const ShadowFP &shadowFP = proc.cast<ShadowFP>();
233
234 fNumDirLights = shadowFP.numLights();
235
236 for (int i = 0; i < fNumDirLights; i++) {
237 const SkVector3 &lightDir = shadowFP.lightDir(i);
238 if (lightDir != fLightDir[i]) {
239 pdman.set3fv(fLightDirUni[i], 1, &lightDir.fX);
240 fLightDir[i] = lightDir;
241 }
242 const SkColor3f &lightColor = shadowFP.lightColor(i);
243 if (lightColor != fLightColor[i]) {
244 pdman.set3fv(fLightColorUni[i], 1, &lightColor.fX);
245 fLightColor[i] = lightColor;
246 }
247 }
248
249 const SkColor3f& ambientColor = shadowFP.ambientColor();
250 if (ambientColor != fAmbientColor) {
251 pdman.set3fv(fAmbientColorUni, 1, &ambientColor.fX);
252 fAmbientColor = ambientColor;
253 }
254 }
255
256 private:
257 SkVector3 fLightDir[SK_MAX_NON_AMBIENT_LIGHTS];
258 GrGLSLProgramDataManager::UniformHandle fLightDirUni[SK_MAX_NON_AMBIENT_ LIGHTS];
259 SkColor3f fLightColor[SK_MAX_NON_AMBIENT_LIGHTS];
260 GrGLSLProgramDataManager::UniformHandle fLightColorUni[SK_MAX_NON_AMBIEN T_LIGHTS];
261
262 SkColor3f fAmbientColor;
263 GrGLSLProgramDataManager::UniformHandle fAmbientColorUni;
264
265 int fNumDirLights;
266 };
267
268 void onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const override {
269 GLSLShadowFP::GenKey(*this, caps, b);
270 }
271
272 const char* name() const override { return "shadowFP"; }
273
274 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
275 inout->mulByUnknownFourComponents();
276 }
277 int32_t numLights() const { return fNumDirLights; }
278 const SkColor3f& ambientColor() const { return fAmbientColor; }
279 const SkVector3& lightDir(int i) const {
280 SkASSERT(i < fNumDirLights);
281 return fLightDir[i];
282 }
283 const SkVector3& lightColor(int i) const {
284 SkASSERT(i < fNumDirLights);
285 return fLightColor[i];
286 }
287
288 private:
289 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new GLSLShadowFP; }
290
291 bool onIsEqual(const GrFragmentProcessor& proc) const override {
292 const ShadowFP& shadowFP = proc.cast<ShadowFP>();
293 if (fAmbientColor != shadowFP.fAmbientColor || fNumDirLights != shadowFP .fNumDirLights) {
294 return false;
295 }
296
297 for (int i = 0; i < fNumDirLights; i++) {
298 if (fLightDir[i] != shadowFP.fLightDir[i] ||
299 fLightColor[i] == shadowFP.fLightColor[i]) {
300 return false;
301 }
302 }
303
304 return true;
305 }
306
307 int fNumDirLights;
308
309 SkVector3 fLightDir[SK_MAX_NON_AMBIENT_LIGHTS];
310 SkColor3f fLightColor[SK_MAX_NON_AMBIENT_LIGHTS];
311 GrTextureAccess fDepthMapAccess[SK_MAX_NON_AMBIENT_LIGHTS];
312 sk_sp<GrTexture> fTexture[SK_MAX_NON_AMBIENT_LIGHTS];
313
314 SkColor3f fAmbientColor;
315 };
316
317 ////////////////////////////////////////////////////////////////////////////
318
319 sk_sp<GrFragmentProcessor> SkShadowShaderImpl::asFragmentProcessor(const AsFPArg s& fpargs) const {
320
321 sk_sp<GrFragmentProcessor> povDepthFP = povDepthShader->asFragmentProcessor( fpargs);
322
323 sk_sp<GrFragmentProcessor> diffuseFP = diffuseShader->asFragmentProcessor(fp args);
324
325 sk_sp<GrFragmentProcessor> shadowfp = sk_make_sp<ShadowFP>(std::move(povDept hFP),
326 std::move(diffuse FP),
327 std::move(fLights ),
328 fpargs.fContext);
329 return shadowfp;
330 }
331
332
333 #endif
334
335 ////////////////////////////////////////////////////////////////////////////
336
337 bool SkShadowShaderImpl::isOpaque() const {
338 return diffuseShader->isOpaque();
339 }
340
341 SkShadowShaderImpl::ShadowShaderContext::ShadowShaderContext(
342 const SkShadowShaderImpl& shader, const ContextRec& rec,
343 SkShader::Context* povDepthContext,
344 SkShader::Context* diffuseContext,
345 void* heapAllocated)
346 : INHERITED(shader, rec)
347 , fPovDepthContext(povDepthContext)
348 , fDiffuseContext(diffuseContext)
349 , fHeapAllocated(heapAllocated) {
350 bool isOpaque = shader.isOpaque();
351
352 // update fFlags
353 uint32_t flags = 0;
354 if (isOpaque && (255 == this->getPaintAlpha())) {
355 flags |= kOpaqueAlpha_Flag;
356 }
357
358 fFlags = flags;
359 }
360
361 SkShadowShaderImpl::ShadowShaderContext::~ShadowShaderContext() {
362 // The dependencies have been created outside of the context on memory that was allocated by
363 // the onCreateContext() method. Call the destructors and free the memory.
364 fPovDepthContext->~Context();
365 fDiffuseContext->~Context();
366
367 sk_free(fHeapAllocated);
368 }
369
370 static inline SkPMColor convert(SkColor3f color, U8CPU a) {
371 if (color.fX <= 0.0f) {
372 color.fX = 0.0f;
373 } else if (color.fX >= 255.0f) {
374 color.fX = 255.0f;
375 }
376
377 if (color.fY <= 0.0f) {
378 color.fY = 0.0f;
379 } else if (color.fY >= 255.0f) {
380 color.fY = 255.0f;
381 }
382
383 if (color.fZ <= 0.0f) {
384 color.fZ = 0.0f;
385 } else if (color.fZ >= 255.0f) {
386 color.fZ = 255.0f;
387 }
388
389 return SkPreMultiplyARGB(a, (int) color.fX, (int) color.fY, (int) color.fZ) ;
390 }
391
392 // larger is better (fewer times we have to loop), but we shouldn't
393 // take up too much stack-space (each one here costs 16 bytes)
394 #define BUFFER_MAX 16
395 void SkShadowShaderImpl::ShadowShaderContext::shadeSpan(int x, int y,
396 SkPMColor result[], int count) {
397 const SkShadowShaderImpl& lightShader = static_cast<const SkShadowShaderImpl &>(fShader);
398
399 SkPMColor diffuse[BUFFER_MAX];
400
401 do {
402 int n = SkTMin(count, BUFFER_MAX);
403
404 fPovDepthContext->shadeSpan(x, y, diffuse, n);
405 fDiffuseContext->shadeSpan(x, y, diffuse, n);
406
407 for (int i = 0; i < n; ++i) {
408
409 SkColor diffColor = SkUnPreMultiply::PMColorToColor(diffuse[i]);
410
411 SkColor3f accum = SkColor3f::Make(0.0f, 0.0f, 0.0f);
412 // This is all done in linear unpremul color space (each component 0 ..255.0f though)
413 for (int l = 0; l < lightShader.fLights->numLights(); ++l) {
414 const SkLights::Light& light = lightShader.fLights->light(l);
415
416 if (SkLights::Light::kAmbient_LightType == light.type()) {
417 accum.fX += light.color().fX * SkColorGetR(diffColor);
418 accum.fY += light.color().fY * SkColorGetG(diffColor);
419 accum.fZ += light.color().fZ * SkColorGetB(diffColor);
420 } else {
421 // scaling by fZ accounts for lighting direction
422 accum.fX += light.color().makeScale(light.dir().fZ).fX * SkC olorGetR(diffColor);
423 accum.fY += light.color().makeScale(light.dir().fZ).fY * SkC olorGetG(diffColor);
424 accum.fZ += light.color().makeScale(light.dir().fZ).fZ * SkC olorGetB(diffColor);
425 }
426 }
427
428 result[i] = convert(accum, SkColorGetA(diffColor));
429 }
430
431 result += n;
432 x += n;
433 count -= n;
434 } while (count > 0);
435 }
436
437 ////////////////////////////////////////////////////////////////////////////
438
439 #ifndef SK_IGNORE_TO_STRING
440 void SkShadowShaderImpl::toString(SkString* str) const {
441 str->appendf("ShadowShader: ()");
442 }
443 #endif
444
445 sk_sp<SkFlattenable> SkShadowShaderImpl::CreateProc(SkReadBuffer& buf) {
446
447 // Discarding SkShader flattenable params
448 bool hasLocalMatrix = buf.readBool();
449 SkAssertResult(!hasLocalMatrix);
450
451 int numLights = buf.readInt();
452
453 SkLights::Builder builder;
454
455 for (int l = 0; l < numLights; ++l) {
456 bool isAmbient = buf.readBool();
457
458 SkColor3f color;
459 if (!buf.readScalarArray(&color.fX, 3)) {
460 return nullptr;
461 }
462
463 if (isAmbient) {
464 builder.add(SkLights::Light(color));
465 } else {
466 SkVector3 dir;
467 if (!buf.readScalarArray(&dir.fX, 3)) {
468 return nullptr;
469 }
470 builder.add(SkLights::Light(color, dir));
471 }
472 }
473
474 sk_sp<SkLights> lights(builder.finish());
475
476 sk_sp<SkShader> povDepthShader(buf.readFlattenable<SkShader>());
477 sk_sp<SkShader> diffuseShader(buf.readFlattenable<SkShader>());
478
479 return sk_make_sp<SkShadowShaderImpl>(std::move(povDepthShader),
480 std::move(diffuseShader),
481 std::move(lights));
482 }
483
484 void SkShadowShaderImpl::flatten(SkWriteBuffer& buf) const {
485 this->INHERITED::flatten(buf);
486
487 buf.writeInt(fLights->numLights());
488 for (int l = 0; l < fLights->numLights(); ++l) {
489 const SkLights::Light& light = fLights->light(l);
490
491 bool isAmbient = SkLights::Light::kAmbient_LightType == light.type();
492
493 buf.writeBool(isAmbient);
494 buf.writeScalarArray(&light.color().fX, 3);
495 if (!isAmbient) {
496 buf.writeScalarArray(&light.dir().fX, 3);
497 }
498 }
499
500 buf.writeFlattenable(povDepthShader.get());
501 buf.writeFlattenable(diffuseShader.get());
502 }
503
504 size_t SkShadowShaderImpl::onContextSize(const ContextRec& rec) const {
505 return sizeof(ShadowShaderContext);
506 }
507
508 SkShader::Context* SkShadowShaderImpl::onCreateContext(const ContextRec& rec,
509 void* storage) const {
510 size_t heapRequired = povDepthShader->contextSize(rec) +
511 diffuseShader->contextSize(rec);
512
513 void* heapAllocated = sk_malloc_throw(heapRequired);
514
515 void* povDepthContextStorage = heapAllocated;
516
517 SkShader::Context* povDepthContext =
518 povDepthShader->createContext(rec, povDepthContextStorage);
519
520 if (!povDepthContext) {
521 sk_free(heapAllocated);
522 return nullptr;
523 }
524
525 void* diffuseContextStorage = (char*)heapAllocated + povDepthShader->context Size(rec);
526
527 SkShader::Context* diffuseContext = diffuseShader->createContext(rec, diffus eContextStorage);
528 if (!diffuseContext) {
529 sk_free(heapAllocated);
530 return nullptr;
531 }
532
533 return new (storage) ShadowShaderContext(*this, rec, povDepthContext, diffus eContext,
534 heapAllocated);
535 }
536
537 ///////////////////////////////////////////////////////////////////////////////
538
539 sk_sp<SkShader> SkShadowShader::Make(sk_sp<SkShader> povDepthShader,
540 sk_sp<SkShader> diffuseShader,
541 sk_sp<SkLights> lights) {
542 if (!povDepthShader || !diffuseShader) {
543 // TODO: Use paint's color in absence of a diffuseShader
544 // TODO: Use a default implementation of normalSource instead
545 return nullptr;
546 }
547
548 return sk_make_sp<SkShadowShaderImpl>(std::move(povDepthShader),
549 std::move(diffuseShader),
550 std::move(lights));
551 }
552
553 ///////////////////////////////////////////////////////////////////////////////
554
555 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkShadowShader)
556 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkShadowShaderImpl)
557 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
558
559 ///////////////////////////////////////////////////////////////////////////////
OLDNEW
« gm/shadowmaps.cpp ('K') | « src/core/SkShadowShader.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698