Rise
The Vieneo Province
Loading...
Searching...
No Matches
AdDiagnostics11.cpp
Go to the documentation of this file.
1#include "AdDiagnostics11.h"
2#include "ShaderBytecode11.h"
3#include "FrameProfiler11.h"
4#include <d3d11_1.h>
5#include <algorithm>
6#include <sstream>
7#include <iomanip>
8#include <cstdio>
9#include <io.h>
10#include <share.h>
11#include <cfloat>
12
13using namespace DirectX;
14using Microsoft::WRL::ComPtr;
15namespace Rendering
16{
17 namespace
18 {
19 XMFLOAT3 Add(XMFLOAT3 a, XMFLOAT3 b, float scale = 1)
20 { return { a.x + b.x * scale, a.y + b.y * scale, a.z + b.z * scale }; }
21 XMFLOAT3 Scale(XMFLOAT3 a, float s) { return { a.x * s, a.y * s, a.z * s }; }
22 float Dot(XMFLOAT3 a, XMFLOAT3 b) { return a.x*b.x+a.y*b.y+a.z*b.z; }
23 float Length(XMFLOAT3 a) { return std::sqrt(Dot(a,a)); }
24 XMFLOAT3 Normalize(XMFLOAT3 a) { return Scale(a,1.f/(std::max)(Length(a),1e-12f)); }
25 XMFLOAT3 Cross(XMFLOAT3 a, XMFLOAT3 b)
26 { return {a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x}; }
27 VertexLayout11 Layout()
28 { VertexLayout11 value;value.stride=sizeof(AdDiagnostics11::Vertex);value.normal=12;value.uv[0]=24;value.uv[1]=32;return value; }
30 {
32 out.position=Add(Scale(a.position,1-t),b.position,t);
33 out.normal=Add(Scale(a.normal,1-t),b.normal,t);
34 out.uv={a.uv.x+(b.uv.x-a.uv.x)*t,a.uv.y+(b.uv.y-a.uv.y)*t};
35 out.logo={a.logo.x+(b.logo.x-a.logo.x)*t,a.logo.y+(b.logo.y-a.logo.y)*t};return out;
36 }
37 std::vector<AdDiagnostics11::Vertex> Clip(std::vector<AdDiagnostics11::Vertex> polygon, int axis, float edge, bool minimum)
38 {
39 std::vector<AdDiagnostics11::Vertex> out;
40 if(polygon.empty())return out;
41 const auto coord=[axis](const AdDiagnostics11::Vertex& p){return axis ? p.logo.y : p.logo.x;};
42 auto a=polygon.back();float da=minimum ? coord(a)-edge : edge-coord(a);
43 for(const auto& b:polygon)
44 {
45 const float db=minimum ? coord(b)-edge : edge-coord(b);
46 if((da>=0)!=(db>=0))out.push_back(Mix(a,b,da/(da-db)));
47 if(db>=0)out.push_back(b);a=b;da=db;
48 }
49 return out;
50 }
51 std::string CSV(const std::string& text)
52 {
53 std::string out="\"";for(char c:text){if(c=='\"')out+='\"';out+=c;}return out+'\"';
54 }
55 uint64_t UnixMilliseconds()
56 {
57 FILETIME time;GetSystemTimeAsFileTime(&time);
58 ULARGE_INTEGER ticks;ticks.LowPart=time.dwLowDateTime;ticks.HighPart=time.dwHighDateTime;
59 return ticks.QuadPart/10000-11644473600000ull;
60 }
61 std::string Utc(uint64_t milliseconds)
62 {
63 ULARGE_INTEGER ticks;ticks.QuadPart=(milliseconds+11644473600000ull)*10000;
64 const FILETIME time{ticks.LowPart,ticks.HighPart};SYSTEMTIME utc{};
65 if(!FileTimeToSystemTime(&time,&utc))return "";
66 char text[32];sprintf_s(text,"%04u-%02u-%02uT%02u:%02u:%02u.%03uZ",
67 unsigned(utc.wYear),unsigned(utc.wMonth),unsigned(utc.wDay),unsigned(utc.wHour),
68 unsigned(utc.wMinute),unsigned(utc.wSecond),unsigned(utc.wMilliseconds));return text;
69 }
70 void Unbind(ID3D11DeviceContext* context)
71 {
72 ID3D11ShaderResourceView* empty[D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT]{};
73 context->PSSetShaderResources(0,UINT(std::size(empty)),empty);
74 context->VSSetShaderResources(0,UINT(std::size(empty)),empty);
75 context->OMSetRenderTargets(0,nullptr,nullptr);
76 }
77 struct Restore
78 {
79 ComPtr<ID3D11DeviceContext1> context;
80 ComPtr<ID3DDeviceContextState> previous;
81 ~Restore(){if(previous){Unbind(context.Get());context->SwapDeviceContextState(previous.Get(),nullptr);}}
82 };
83 }
86 {
87 if(value==enabled)return;
88 if(!value){Checkpoint(sourceSeconds,true);StopLog();ResetResources();status="off";}
89 else
90 {
94 sessionId=std::to_string(GetCurrentProcessId())+"-"+std::to_string(GetTickCount64())+"-"+std::to_string(sessionAnchorUnixMs);
95 logPath="outputs/ad-viewability-"+sessionId+".csv";
96 writer=std::thread(&AdDiagnostics11::LogWorker,this);status="starting";
97 }
99 }
101 {
103 opacityView.Reset();opacityTarget.Reset();opacityTexture.Reset();sceneTarget.Reset();raster.Reset();noColor.Reset();
104 glassView.Reset();glassTarget.Reset();glassTexture.Reset();opacityBlend.Reset();overlays.clear();overlayFailure.clear();
105 for(auto& program:overlayPrograms)program.Reset();
106 referenceDepth.Reset();visibleDepth.Reset();meshes.clear();candidates.clear();
107 for(auto& pair:programs)for(auto& program:pair)program.Reset();
108 for(auto& frame:ring){frame.candidates.clear();frame.pending=false;for(auto& item:frame.queries)for(auto& query:item)query.Reset();}
110 }
111 void AdDiagnostics11::SyncPlacement(unsigned slot,uint64_t entity,const std::string& creative)
112 {
113 if(slot>=4096)return; // Diagnostic registry budget, independent of server slots.
114 if(slot>=vehicles.size())vehicles.resize(size_t(slot)+1);
115 auto& identity=vehicles[slot];
116 if(identity.entity!=entity || identity.creative!=creative)
117 {identity.entity=entity;identity.creative=creative;++identity.generation;}
118 }
120 {
121 if(!view)return nullptr;
122 if(metadataDevice.Get()!=device.Native())
123 {creatives.clear();metadataDevice=device.Native();metadataFrame=-1;}
125 auto found=std::find_if(creatives.begin(),creatives.end(),[&](const CachedCreative& item){return item.view.Get()==view;});
126 if(found==creatives.end())
127 {
128 unsigned pending=0;for(const auto& item:creatives)pending+=!item.ready && !item.failed;
129 if(pending>=2)return nullptr;
130 if(creatives.size()>=MaximumCreatives)
131 {
132 const auto evict=std::find_if(creatives.begin(),creatives.end(),[](const CachedCreative& item){return item.ready || item.failed;});
133 if(evict==creatives.end())return nullptr;creatives.erase(evict);
134 }
135 creatives.emplace_back();found=std::prev(creatives.end());found->view=view;
136 auto& item=*found;D3D11_SHADER_RESOURCE_VIEW_DESC srv{};view->GetDesc(&srv);
137 ComPtr<ID3D11Resource> resource;view->GetResource(&resource);ComPtr<ID3D11Texture2D> texture;
138 if(srv.ViewDimension!=D3D11_SRV_DIMENSION_TEXTURE2D || FAILED(resource.As(&texture)))
139 {item.failed=true;return nullptr;}
140 D3D11_TEXTURE2D_DESC desc{};texture->GetDesc(&desc);
141 const UINT level=srv.Texture2D.MostDetailedMip;
142 desc.Width=(std::max)(1u,desc.Width>>level);desc.Height=(std::max)(1u,desc.Height>>level);
143 const bool rgba=desc.Format==DXGI_FORMAT_R8G8B8A8_UNORM || desc.Format==DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
144 item.bgra=desc.Format==DXGI_FORMAT_B8G8R8A8_UNORM || desc.Format==DXGI_FORMAT_B8G8R8A8_UNORM_SRGB || desc.Format==DXGI_FORMAT_B8G8R8X8_UNORM;
145 item.opaque=desc.Format==DXGI_FORMAT_B8G8R8X8_UNORM;
146 item.srgb=srv.Format==DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || srv.Format==DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
147 if((!rgba && !item.bgra) || desc.SampleDesc.Count!=1 || uint64_t(desc.Width)*desc.Height>MaximumCreativePixels)
148 {item.failed=true;return nullptr;}
149 item.metadata.width=desc.Width;item.metadata.height=desc.Height;
150 desc.MipLevels=desc.ArraySize=1;desc.Usage=D3D11_USAGE_STAGING;
151 desc.BindFlags=desc.MiscFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
152 if(FAILED(device.Native()->CreateTexture2D(&desc,nullptr,&item.staging)))
153 {item.failed=true;return nullptr;}
154 device.Context()->CopySubresourceRegion(item.staging.Get(),0,0,0,0,texture.Get(),level,nullptr);
155 // Never Map immediately after issuing the copy or flush to force it ready.
156 return nullptr;
157 }
158 auto& item=*found;if(item.ready)return &item.metadata;if(item.failed || !metadataBudget)return nullptr;
159 D3D11_MAPPED_SUBRESOURCE mapped{};
160 const HRESULT hr=device.Context()->Map(item.staging.Get(),0,D3D11_MAP_READ,D3D11_MAP_FLAG_DO_NOT_WAIT,&mapped);
161 if(hr==DXGI_ERROR_WAS_STILL_DRAWING)return nullptr;
162 if(FAILED(hr)){item.failed=true;item.staging.Reset();return nullptr;}
163 static const auto linear=[]{
164 std::array<double,256> table{};
165 for(unsigned i=0;i<256;++i){const double c=i/255.;table[i]=c<=.04045 ? c/12.92 : std::pow((c+.055)/1.055,2.4);}
166 return table;
167 }();
168 auto& stats=item.metadata;
169 const unsigned rows=(std::min)(stats.height-item.row,metadataBudget/stats.width);
170 for(unsigned y=item.row;y<item.row+rows;++y)
171 {
172 const auto* row=static_cast<const uint8_t*>(mapped.pData)+size_t(y)*mapped.RowPitch;
173 for(unsigned x=0;x<stats.width;++x)
174 {
175 const auto* p=row+x*4;const unsigned r=p[item.bgra ? 2 : 0],g=p[1],b=p[item.bgra ? 0 : 2];
176 const double alpha=item.opaque ? 1. : p[3]/255.;
177 stats.alphaPixels+=alpha;item.red+=alpha*(item.srgb ? linear[r] : r/255.);
178 item.green+=alpha*(item.srgb ? linear[g] : g/255.);item.blue+=alpha*(item.srgb ? linear[b] : b/255.);
179 item.luminance+=alpha*(linear[r]*.2126+linear[g]*.7152+linear[b]*.0722);
180 for(unsigned channel=0;channel<4;++channel){stats.hash^=p[channel];stats.hash*=1099511628211ull;}
181 if(alpha>.01){item.minX=(std::min)(item.minX,x);item.minY=(std::min)(item.minY,y);item.maxX=(std::max)(item.maxX,x);item.maxY=(std::max)(item.maxY,y);}
182 }
183 }
184 device.Context()->Unmap(item.staging.Get(),0);item.row+=rows;metadataBudget-=rows*stats.width;
185 if(item.row<stats.height)return nullptr;
186 item.ready=true;item.staging.Reset();stats.empty=item.minX==UINT_MAX;
187 stats.hash^=uint64_t(stats.width)<<32|stats.height;
188 if(!stats.empty)
189 {
190 stats.bounds={float(item.minX)/stats.width,float(item.minY)/stats.height,float(item.maxX+1)/stats.width,float(item.maxY+1)/stats.height};
191 stats.fillFraction=(std::min)(1.,stats.alphaPixels/(double(item.maxX-item.minX+1)*(item.maxY-item.minY+1)));
192 stats.meanColor={float(item.red/stats.alphaPixels),float(item.green/stats.alphaPixels),float(item.blue/stats.alphaPixels),float((std::min)(1.,stats.fillFraction))};
193 stats.meanLuminance=item.luminance/stats.alphaPixels;
194 }
195 return &stats;
196 }
198 {
199 ResetResources();native=device.Native();ComPtr<ID3D11Device1> device1;
200 HRESULT hr=native.As(&device1);if(FAILED(hr))return hr;
201 const D3D_FEATURE_LEVEL level=native->GetFeatureLevel();
202 hr=device1->CreateDeviceContextState(0,&level,1,D3D11_SDK_VERSION,__uuidof(ID3D11Device),nullptr,&passState);
203 if(FAILED(hr))return hr;
204 const auto elements=Layout().Elements();
205 const unsigned materials[]={4,5,2,3};
206 for(unsigned material=0;material<4;++material)
207 {
208 const std::string suffix=std::to_string(materials[material]);
209 const auto vs=ReadShaderBytecode11("AdViewability-AdVertex"+suffix+"-1.cso");
210 for(unsigned variant=0;variant<4;++variant)
211 {
212 const auto ps=ReadShaderBytecode11("AdViewability-AdPixel"+suffix+"-"+std::to_string(1u<<variant)+".cso");
213 hr=programs[material][variant].Create(native.Get(),vs.data(),vs.size(),ps.data(),ps.size(),elements.data(),UINT(elements.size()));
214 if(FAILED(hr))return hr;
215 }
216 }
217 VertexLayout11 glassLayout;glassLayout.stride=32;glassLayout.normal=12;glassLayout.uv[0]=24;
218 const auto glassElements=glassLayout.Elements();
219 for(unsigned i=0;i<overlayPrograms.size();++i)
220 {
221 const auto suffix=std::to_string(i==2 ? 13 : 8+i);
222 const auto vs=ReadShaderBytecode11("AdGlassOpacity-AdGlassVertex"+suffix+"-1.cso");
223 const auto ps=ReadShaderBytecode11("AdGlassOpacity-AdGlassPixel"+suffix+"-1.cso");
224 hr=overlayPrograms[i].Create(native.Get(),vs.data(),vs.size(),ps.data(),ps.size(),glassElements.data(),UINT(glassElements.size()));
225 if(FAILED(hr))return hr;
226 }
227 D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_NONE;rs.DepthClipEnable=TRUE;rs.MultisampleEnable=TRUE;
228 if(FAILED(hr=native->CreateRasterizerState(&rs,&raster)))return hr;
229 D3D11_BLEND_DESC bs{};if(FAILED(hr=native->CreateBlendState(&bs,&noColor)))return hr;
230 auto& blend=bs.RenderTarget[0];blend.BlendEnable=TRUE;blend.SrcBlend=D3D11_BLEND_SRC_ALPHA;
231 blend.DestBlend=D3D11_BLEND_INV_SRC_ALPHA;blend.BlendOp=D3D11_BLEND_OP_ADD;
232 blend.SrcBlendAlpha=D3D11_BLEND_ONE;blend.DestBlendAlpha=D3D11_BLEND_ZERO;blend.BlendOpAlpha=D3D11_BLEND_OP_ADD;
233 blend.RenderTargetWriteMask=D3D11_COLOR_WRITE_ENABLE_RED;
234 if(FAILED(hr=native->CreateBlendState(&bs,&opacityBlend)))return hr;
235 D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthFunc=D3D11_COMPARISON_ALWAYS;
236 if(FAILED(hr=native->CreateDepthStencilState(&ds,&referenceDepth)))return hr;
237 ds.DepthEnable=TRUE;ds.DepthWriteMask=D3D11_DEPTH_WRITE_MASK_ZERO;ds.DepthFunc=D3D11_COMPARISON_LESS_EQUAL;
238 ds.StencilEnable=TRUE;ds.StencilReadMask=255;ds.StencilWriteMask=0;
239 ds.FrontFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_COMPARISON_GREATER};ds.BackFace=ds.FrontFace;
240 if(FAILED(hr=native->CreateDepthStencilState(&ds,&visibleDepth)))return hr;
241 for(auto& frame:ring)for(auto& item:frame.queries)for(auto& query:item)
242 {D3D11_QUERY_DESC desc{D3D11_QUERY_OCCLUSION,0};if(FAILED(hr=native->CreateQuery(&desc,&query)))return hr;}
243 status="IAB/MRC threshold diagnostics (not audited)";return S_OK;
244 }
245 void AdDiagnostics11::BeginFrame(RenderDevice& device,double now,bool frameEligible,const char* blocker)
246 {
248 frameBlocker=frameEligible ? "" : (blocker ? blocker : "view inactive/covered");
249 if(!enabled)return;
250 ProfileScope11 timing("Ad diagnostics maintenance",false);
252 if(initializationFailed && native.Get()==device.Native())return;
253 if(native.Get()!=device.Native())
254 {
255 if(FAILED(Initialize(device))){status="GPU measurement unavailable";ResetResources();native=device.Native();initializationFailed=true;return;}
257 }
259 Poll(device,now);tracker.Expire(now);Checkpoint(now);
260 if(now<nextPoll)return;
261 // Avoid repeatedly sampling the same phase of an animated campaign.
262 // Geometry/appearance remain sampled diagnostics, not exact attention.
265 if(!eligible)return;
267 collecting=true;
268 }
269 std::vector<std::shared_ptr<AdDiagnostics11::Patch>>& AdDiagnostics11::Mesh(RenderDevice& device,Geometry11& geometry,unsigned first,unsigned count,const XMFLOAT4& bounds,unsigned frontConvention)
270 {
271 Microsoft::WRL::ComPtr<ID3D11Buffer> sourceBuffer;
272 geometry.NativeBuffer(device.Context(),&sourceBuffer);
273 for(auto& entry:meshes)if(entry.source==&geometry && entry.sourceBuffer==sourceBuffer &&
274 entry.revision==geometry.Revision() && entry.first==first && entry.count==count && entry.frontConvention==frontConvention && !memcmp(&entry.bounds,&bounds,sizeof(bounds)))return entry.patches;
275 if(meshes.size()>=256)meshes.pop_front();
276 meshes.emplace_back();auto& entry=meshes.back();entry.source=&geometry;entry.sourceBuffer=sourceBuffer;entry.revision=geometry.Revision();entry.first=first;entry.count=count;entry.bounds=bounds;
277 entry.frontConvention=frontConvention;
278 const auto& bytes=geometry.Bytes();
279 if(first>bytes.size()/sizeof(Vertex) || count>(bytes.size()/sizeof(Vertex)-first)/3)return entry.patches;
280 for(unsigned triangle=0;triangle<count;++triangle)
281 {
282 Vertex p[3];memcpy(p,bytes.data()+size_t(first+triangle*3)*sizeof(Vertex),sizeof(p));
283 const XMFLOAT3 a=Add(p[1].position,p[0].position,-1),b=Add(p[2].position,p[0].position,-1);
284 const XMFLOAT2 du{p[1].logo.x-p[0].logo.x,p[1].logo.y-p[0].logo.y},dv{p[2].logo.x-p[0].logo.x,p[2].logo.y-p[0].logo.y};
285 const float determinant=du.x*dv.y-du.y*dv.x;
286 if(!std::isfinite(determinant) || std::abs(determinant)<1e-9f)continue;
287 auto polygon=Clip(Clip(Clip(Clip({p[0],p[1],p[2]},0,bounds.x,true),0,bounds.z,false),1,bounds.y,true),1,bounds.w,false);
288 if(polygon.size()<3)continue;
289 const auto u=Scale(Add(Scale(a,dv.y),b,-du.y),1/determinant);
290 const auto v=Scale(Add(Scale(b,du.x),a,-dv.x),1/determinant);
291 const auto origin=Add(Add(p[0].position,u,-p[0].logo.x),v,-p[0].logo.y);
292 auto normal=Normalize(Cross(u,v));const auto authored=Add(Add(p[0].normal,p[1].normal),p[2].normal);
293 if(frontConvention)
294 {
295 // City vertices already include planetary placement; their
296 // legacy lighting normals do not. Match actual raster facing.
297 normal=Normalize(Cross(a,b));if(frontConvention==2)normal=Scale(normal,-1);
298 }
299 else if(Dot(normal,authored)<0)normal=Scale(normal,-1);
300 std::shared_ptr<Patch> patch;
301 const float tolerance=(std::max)(1e-6f,(Length(u)+Length(v))*.001f);
302 for(auto& test:entry.patches)if(Length(Add(test->origin,origin,-1))<tolerance &&
303 Length(Add(test->u,u,-1))<tolerance && Length(Add(test->v,v,-1))<tolerance && Dot(test->normal,normal)>.999f){patch=test;break;}
304 if(!patch){patch=std::make_shared<Patch>();patch->origin=origin;patch->u=u;patch->v=v;patch->normal=normal;entry.patches.push_back(patch);}
305 // Keep the original production triangles for exact coplanar depth.
306 // Only CPU bounds/adjacency use retriangulated UV clipping.
307 patch->vertices.insert(patch->vertices.end(),std::begin(p),std::end(p));
308 for(size_t i=1;i+1<polygon.size();++i)
309 {patch->bounds.push_back(polygon[0]);patch->bounds.push_back(polygon[i]);patch->bounds.push_back(polygon[i+1]);}
310 }
311 // Join adjoining facets only when they continue the same UV creative.
312 // Shared geometry alone must not merge repeated logos or opposite sides.
313 using PointKey=std::array<int64_t,5>;
314 using EdgeKey=std::pair<PointKey,PointKey>;
315 struct EdgeRef { unsigned patch; float side; };
316 std::map<EdgeKey,std::vector<EdgeRef>> edges;
317 std::vector<unsigned> parent(entry.patches.size());
318 const auto root=[&](unsigned i){while(parent[i]!=i){parent[i]=parent[parent[i]];i=parent[i];}return i;};
319 const auto key=[](const Vertex& v)->PointKey{return {std::llround(v.position.x*1e6),std::llround(v.position.y*1e6),
320 std::llround(v.position.z*1e6),std::llround(v.logo.x*1e5),std::llround(v.logo.y*1e5)};};
321 for(unsigned i=0;i<parent.size();++i)parent[i]=i;
322 for(unsigned i=0;i<entry.patches.size();++i)
323 {
324 auto& patch=*entry.patches[i];XMFLOAT3 center{};float weight=0;
325 for(size_t t=0;t+2<patch.bounds.size();t+=3)
326 {
327 const auto* triangle=patch.bounds.data()+t;
328 const float area=Length(Cross(Add(triangle[1].position,triangle[0].position,-1),Add(triangle[2].position,triangle[0].position,-1)));
329 center=Add(center,Scale(Add(Add(triangle[0].position,triangle[1].position),triangle[2].position),area/3));weight+=area;
330 for(unsigned e=0;e<3;++e)
331 {
332 const auto& a=triangle[e];const auto& b=triangle[(e+1)%3];const auto& c=triangle[(e+2)%3];
333 auto ka=key(a),kb=key(b);float side=(b.logo.x-a.logo.x)*(c.logo.y-a.logo.y)-(b.logo.y-a.logo.y)*(c.logo.x-a.logo.x);
334 if(ka==kb || std::abs(side)<1e-10f)continue;
335 if(kb<ka){std::swap(ka,kb);side=-side;}
336 auto& matches=edges[{ka,kb}];
337 for(const auto& match:matches)if(match.patch!=i && side*match.side<0 && Dot(patch.normal,entry.patches[match.patch]->normal)>.5f)
338 {
339 const auto ra=root(i),rb=root(match.patch);
340 parent[(std::max)(ra,rb)]=(std::min)(ra,rb);
341 }
342 matches.push_back({i,side});
343 }
344 }
345 patch.facets.push_back({patch.origin,patch.u,patch.v,patch.normal,Scale(center,1.f/(std::max)(weight,1e-12f)),
346 0,unsigned(patch.vertices.size()),0,unsigned(patch.bounds.size())});
347 }
348 std::vector<std::shared_ptr<Patch>> connected;
349 for(unsigned i=0;i<entry.patches.size();++i)
350 {
351 const auto r=root(i);auto& patch=entry.patches[i];
352 if(r==i)connected.push_back(patch);
353 else
354 {
355 auto& group=entry.patches[r];
356 for(auto& facet:patch->facets){facet.first+=unsigned(group->vertices.size());facet.boundsFirst+=unsigned(group->bounds.size());}
357 group->vertices.insert(group->vertices.end(),patch->vertices.begin(),patch->vertices.end());
358 group->bounds.insert(group->bounds.end(),patch->bounds.begin(),patch->bounds.end());
359 group->facets.insert(group->facets.end(),patch->facets.begin(),patch->facets.end());
360 }
361 }
362 entry.patches=std::move(connected);
363 for(auto& patch:entry.patches)
364 {
365 const UINT size=UINT(patch->vertices.size()*sizeof(Vertex));
366 if(FAILED(patch->geometry.Create(device.Native(),size,false)))continue;
367 void* data=nullptr;if(SUCCEEDED(patch->geometry.Lock(0,size,&data))){memcpy(data,patch->vertices.data(),size);patch->geometry.Unlock();}
368 }
369 return entry.patches;
370 }
371 void AdDiagnostics11::RegisterDraw(RenderDevice& device,const AdViewability::Placement& placement,unsigned slot,
372 Geometry11& geometry,unsigned first,unsigned count,unsigned material,const XMFLOAT4X4& world,
373 const XMFLOAT4X4& view,const XMFLOAT4X4& projection,float distanceKm)
374 {
375 if(!collecting || slot>=vehicles.size() || material<4 || material>5)return;
376 if(vehicles[slot].entity!=placement.entity || vehicles[slot].creative!=placement.creative || placement.creative.empty())return;
377 ProfileAccumulatedCpu11 timing("Ad diagnostics candidate preparation");
378 const auto* metadata=PrepareCreative(device,device.Draws().Materials().Values().Texture("OverlayMap"));
379 RegisterPreparedDraw(device,placement,slot,metadata,{},0,0,{},geometry,first,count,material-4,world,view,projection,distanceKm);
380 }
382 const CreativeMetadata* metadata,const std::weak_ptr<void>& lifetime,unsigned animationFrame,unsigned animationFrames,
383 const AnimatedAdMetadata::Summary& average,Geometry11& geometry,unsigned first,unsigned count,unsigned material,
384 const XMFLOAT4X4& world,const XMFLOAT4X4& view,const XMFLOAT4X4& projection,float distanceKm)
385 {
386 if(!collecting || placement.kind!=AdViewability::PlacementKind::BuildingSign || placement.creative.empty() ||
387 lifetime.expired() || material<2 || material>3)return;
388 ProfileAccumulatedCpu11 timing("Ad diagnostics sign preparation");
389 RegisterPreparedDraw(device,placement,UINT_MAX,metadata,lifetime,animationFrame,animationFrames,average,
390 geometry,first,count,material,world,view,projection,distanceKm);
391 }
393 unsigned slot,const CreativeMetadata* metadata,const std::weak_ptr<void>& lifetime,unsigned animationFrame,unsigned animationFrames,
394 const AnimatedAdMetadata::Summary& average,Geometry11& geometry,unsigned first,unsigned count,unsigned program,
395 const XMFLOAT4X4& world,const XMFLOAT4X4& view,const XMFLOAT4X4& projection,float distanceKm)
396 {
397 const auto& vp=device.Draws().Viewport();
398 if(!metadata || metadata->empty)
399 {
400 AdViewability::Observation value;value.seconds=sourceSeconds;value.distanceKm=distanceKm;value.screenPixels=double(vp.Width)*vp.Height;
401 value.measurable=metadata!=nullptr;value.sizeRejected=metadata && metadata->empty;
402 value.creativeHash=placement.creativeHash;value.animationFrame=animationFrame;value.animationFrames=animationFrames;
404 if(metadata){value.creativeHash=metadata->hash;value.sourceWidth=metadata->width;value.sourceHeight=metadata->height;
406 value.sourceBounds={metadata->bounds.x,metadata->bounds.y,metadata->bounds.z,metadata->bounds.w};}
407 tracker.Observe(placement,value);return;
408 }
409 const unsigned frontConvention=program>=2 ? (device.Draws().Pipeline().raster.FrontCounterClockwise ? 2u : 1u) : 0u;
410 const auto& patches=Mesh(device,geometry,first,count,metadata->bounds,frontConvention);
411 if(patches.empty())return;
412 const XMMATRIX worldView=XMLoadFloat4x4(&world)*XMLoadFloat4x4(&view),wvp=worldView*XMLoadFloat4x4(&projection);
413 const auto normalMatrix=XMMatrixTranspose(XMMatrixInverse(nullptr,worldView));
414 std::vector<XMFLOAT2> screenPoints;
415 unsigned surface=0;
416 for(const auto& patch:patches)
417 {
418 Candidate candidate;candidate.placement=placement;candidate.placement.surface=surface++;candidate.slot=slot;
419 candidate.generation=slot<vehicles.size() ? vehicles[slot].generation : 0;
420 candidate.creativeLifetime=lifetime;candidate.patch=patch;candidate.material=program;
421 auto& observation=candidate.observation;observation.seconds=sourceSeconds;observation.distanceKm=distanceKm;
422 observation.screenPixels=double(vp.Width)*vp.Height;
423 observation.sourceAlphaPixels=metadata->alphaPixels;observation.sourceMeanLuminance=metadata->meanLuminance;
424 observation.sourceFillFraction=metadata->fillFraction;observation.creativeHash=metadata->hash;
425 observation.sourceWidth=metadata->width;observation.sourceHeight=metadata->height;
426 observation.sourceBounds={metadata->bounds.x,metadata->bounds.y,metadata->bounds.z,metadata->bounds.w};
427 observation.animationFrame=animationFrame;observation.animationFrames=animationFrames;
428 observation.animationMeanLuminance=average.luminance;observation.animationAlphaFraction=average.alphaFraction;
429 observation.animationAnalyzedFraction=average.analyzedFraction;
430 screenPoints.clear();screenPoints.reserve(patch->bounds.size());
431 XMFLOAT2 minimum{FLT_MAX,FLT_MAX},maximum{-FLT_MAX,-FLT_MAX};
432 for(const auto& vertex:patch->bounds)
433 {
434 XMFLOAT4 clip;XMStoreFloat4(&clip,XMVector4Transform(XMVectorSet(vertex.position.x,vertex.position.y,vertex.position.z,1),wvp));
435 if(!std::isfinite(clip.x) || !std::isfinite(clip.y) || !std::isfinite(clip.z) || !std::isfinite(clip.w) || clip.w<=0 || clip.z<=0 || clip.z>=clip.w)
436 {observation.projectionInvalid=true;screenPoints.push_back({});continue;}
437 const XMFLOAT2 point{(clip.x/clip.w+1)*vp.Width*.5f,(1-clip.y/clip.w)*vp.Height*.5f};screenPoints.push_back(point);
438 minimum.x=(std::min)(minimum.x,point.x);minimum.y=(std::min)(minimum.y,point.y);
439 maximum.x=(std::max)(maximum.x,point.x);maximum.y=(std::max)(maximum.y,point.y);
440 if(point.x<0 || point.y<0 || point.x>vp.Width || point.y>vp.Height)observation.clipped=true;
441 }
442 for(size_t i=0;i+2<screenPoints.size();i+=3)
443 {
444 const auto a=screenPoints[i],b=screenPoints[i+1],c=screenPoints[i+2];
445 candidate.estimatedPixels+=std::abs(double(b.x-a.x)*(c.y-a.y)-double(b.y-a.y)*(c.x-a.x))*.5;
446 }
447 if(!observation.projectionInvalid)
448 {observation.projectedWidthPixels=maximum.x-minimum.x;observation.projectedHeightPixels=maximum.y-minimum.y;}
449 const auto project=[&](XMFLOAT3 point){XMFLOAT4 p;XMStoreFloat4(&p,XMVector4Transform(XMVectorSet(point.x,point.y,point.z,1),wvp));return XMFLOAT2{p.x/(std::max)(1e-9f,p.w)*vp.Width,-p.y/(std::max)(1e-9f,p.w)*vp.Height};};
450 // Test angles per facet; one small steep piece must not veto a whole
451 // creative. The readout describes the largest front-facing facet.
452 double mainArea=-1;
453 for(unsigned index=0;index<patch->facets.size();++index)
454 {
455 const auto& facet=patch->facets[index];
456 XMFLOAT3 normal;XMStoreFloat3(&normal,XMVector3Normalize(XMVector3TransformNormal(XMLoadFloat3(&facet.normal),normalMatrix)));
457 XMFLOAT3 cameraCenter;XMStoreFloat3(&cameraCenter,XMVector3TransformCoord(XMLoadFloat3(&facet.center),worldView));
458 const auto towardEye=Normalize(Scale(cameraCenter,-1));const auto axisRight=Normalize(Cross({0,1,0},towardEye));
459 const auto axisUp=Normalize(Cross(towardEye,axisRight));const float facing=Dot(normal,towardEye);
460 const double yaw=std::atan2(Dot(normal,axisRight),facing)*180/XM_PI,pitch=std::atan2(Dot(normal,axisUp),facing)*180/XM_PI;
461 const auto p=project(facet.center),up=project(Add(facet.center,facet.v,-.1f)),right=project(Add(facet.center,facet.u,.1f));
462 const double roll=std::atan2(up.x-p.x,p.y-up.y)*180/XM_PI;
463 if(facing<=0)continue;
464 candidate.frontFacets.push_back(index);
465 const bool mirrored=(right.x-p.x)*(up.y-p.y)-(right.y-p.y)*(up.x-p.x)>=0;
466 if(!mirrored && std::abs(yaw)<=AdViewability::Policy::MaximumAngleDegrees &&
468 candidate.angleFacets.push_back(index);
469 double area=0;
470 for(unsigned t=facet.boundsFirst;t+2<facet.boundsFirst+facet.boundsCount;t+=3)
471 {const auto a=screenPoints[t],b=screenPoints[t+1],c=screenPoints[t+2];area+=std::abs(double(b.x-a.x)*(c.y-a.y)-double(b.y-a.y)*(c.x-a.x))*.5;}
472 if(area>mainArea){mainArea=area;observation.yaw=yaw;observation.pitch=pitch;observation.roll=roll;observation.mirrored=mirrored;}
473 }
474 if(candidate.frontFacets.empty())
475 {observation.backFacing=true;tracker.Observe(candidate.placement,observation);continue;}
476 if(observation.projectionInvalid)
477 {tracker.Observe(candidate.placement,observation);continue;}
478 if(maximum.x<=0 || maximum.y<=0 || minimum.x>=vp.Width || minimum.y>=vp.Height)
479 {observation.referencePixels=candidate.estimatedPixels;tracker.Observe(candidate.placement,observation);continue;}
480 if(observation.clipped)
481 {
482 // Fit the FULL intended area into the reference viewport only.
483 // Visible queries retain production coordinates, depth and UI.
484 candidate.referenceScale=(std::min)(1.f,.95f*(std::min)(vp.Width/(maximum.x-minimum.x),vp.Height/(maximum.y-minimum.y)));
485 if(!std::isfinite(candidate.referenceScale) || candidate.referenceScale<.01f)
486 {observation.measurable=false;tracker.Observe(candidate.placement,observation);continue;}
487 const float cx=(minimum.x+maximum.x)/vp.Width-1,cy=1-(minimum.y+maximum.y)/vp.Height;
488 candidate.referenceTransform={candidate.referenceScale,-cx*candidate.referenceScale,-cy*candidate.referenceScale,0};
489 }
490 // Admit small branded placements for diagnostic exposure; the
491 // separate 1.5% standard gate is evaluated after GPU measurement.
493 {
494 // These are CPU upper bounds, not claimed GPU visibility.
495 observation.sizeRejected=true;observation.referencePixels=candidate.estimatedPixels;observation.visiblePixels=observation.clearPixels=0;
496 tracker.Observe(candidate.placement,observation);continue;
497 }
498 candidate.parameters=device.Draws().Materials().Values();
499 candidate.parameters.Set("adBounds",metadata->bounds);candidate.parameters.Set("adReferenceColor",metadata->meanColor);
500 candidate.parameters.Set("adReferenceTransform",candidate.referenceTransform);
501 // Bound retained preparation state as well as the GPU query pool.
502 if(candidates.size()>=MaximumCandidates*4)
503 {
504 auto smallest=std::min_element(candidates.begin(),candidates.end(),[](const Candidate& a,const Candidate& b){return a.estimatedPixels<b.estimatedPixels;});
505 if(smallest->estimatedPixels>=candidate.estimatedPixels)
506 {observation.measurable=false;tracker.Observe(candidate.placement,observation);++dropped;continue;}
507 smallest->observation.measurable=false;tracker.Observe(smallest->placement,smallest->observation);++dropped;
508 *smallest=std::move(candidate);
509 }
510 else candidates.push_back(std::move(candidate));
511 }
512 }
514 {
515 if(!collecting || candidates.empty())return S_FALSE;
516 ProfileScope11 timing("Ad diagnostics depth capture");
517 ComPtr<ID3D11DepthStencilView> depth;sceneTarget.Reset();device.Context()->OMGetRenderTargets(1,&sceneTarget,&depth);
518 if(!depth)return E_UNEXPECTED;ComPtr<ID3D11Resource> resource;depth->GetResource(&resource);
519 ComPtr<ID3D11Texture2D> source;if(FAILED(resource.As(&source)))return E_UNEXPECTED;
520 D3D11_TEXTURE2D_DESC desc{};source->GetDesc(&desc);viewport=device.Draws().Viewport();
521 if(!opacityTexture || opaqueDepth.Description().Width!=desc.Width || opaqueDepth.Description().Height!=desc.Height ||
522 opaqueDepth.Description().SampleDesc.Count!=desc.SampleDesc.Count || opaqueDepth.Description().SampleDesc.Quality!=desc.SampleDesc.Quality)
523 {
524 HRESULT hr=opaqueDepth.Create(native.Get(),desc.Width,desc.Height,desc.SampleDesc);if(FAILED(hr))return hr;
525 desc.Format=DXGI_FORMAT_R8_UNORM;desc.BindFlags=D3D11_BIND_RENDER_TARGET|D3D11_BIND_SHADER_RESOURCE;
526 desc.MiscFlags=desc.CPUAccessFlags=0;desc.Usage=D3D11_USAGE_DEFAULT;desc.MipLevels=desc.ArraySize=1;
527 opacityTexture.Reset();opacityTarget.Reset();opacityView.Reset();
528 glassTexture.Reset();glassTarget.Reset();glassView.Reset();
529 if(FAILED(hr=native->CreateTexture2D(&desc,nullptr,&opacityTexture)) ||
530 FAILED(hr=native->CreateRenderTargetView(opacityTexture.Get(),nullptr,&opacityTarget)) ||
531 FAILED(hr=native->CreateShaderResourceView(opacityTexture.Get(),nullptr,&opacityView)) ||
532 FAILED(hr=native->CreateTexture2D(&desc,nullptr,&glassTexture)) ||
533 FAILED(hr=native->CreateRenderTargetView(glassTexture.Get(),nullptr,&glassTarget)) ||
534 FAILED(hr=native->CreateShaderResourceView(glassTexture.Get(),nullptr,&glassView)))return hr;
535 }
536 // Destination is separate from the scene and never CPU-mapped.
537 device.Context()->CopyResource(opaqueDepth.Texture(),source.Get());
538 const float zero[4]{};device.Context()->ClearRenderTargetView(opacityTarget.Get(),zero);device.Context()->ClearRenderTargetView(glassTarget.Get(),zero);sceneCaptured=true;return S_OK;
539 }
541 {
542 if(!collecting || !sceneCaptured)return;
543 if(FAILED(result))overlayFailure="wet-glass exclusion unavailable";
544 else wetGlassExcluded=result==S_OK;
545 }
546 void AdDiagnostics11::RegisterOverlayDraw(RenderDevice& device,Geometry11& geometry,unsigned first,unsigned count,unsigned material)
547 {
548 if(!collecting || !sceneCaptured)return;
549 ProfileAccumulatedCpu11 timing("Ad diagnostics overlay preparation");
550 const auto& blend=device.Draws().Pipeline().blend.RenderTarget[0];
551 if(!blend.BlendEnable || blend.SrcBlend!=D3D11_BLEND_SRC_ALPHA || blend.DestBlend!=D3D11_BLEND_INV_SRC_ALPHA)
552 {overlayFailure="cockpit additive/non-alpha effect unsupported";return;}
553 if(overlays.size()>=128){overlayFailure="cockpit overlay budget exceeded";return;}
554 if(material!=8 && material!=9 && material!=13){overlayFailure="cockpit overlay material unsupported";return;}
555 OverlayDraw draw;draw.first=first;draw.count=count;draw.material=material==13 ? 2 : material-8;
556 geometry.NativeBuffer(device.Context(),&draw.buffer);device.Context()->RSGetState(&draw.raster);
557 draw.viewport=device.Draws().Viewport();draw.parameters=device.Draws().Materials().Values();
558 UINT countRects=D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;draw.scissors.resize(countRects);
559 device.Context()->RSGetScissorRects(&countRects,draw.scissors.data());draw.scissors.resize(countRects);
560 overlays.push_back(std::move(draw));
561 }
562 void AdDiagnostics11::FinishScene(RenderDevice& device,bool weatherMeasured,const std::vector<XMFLOAT4>& uiRects,const char* uiBlocker)
563 {
564 if(!enabled)return;
565 const bool blocked=uiBlocker && *uiBlocker;
566 if(uiBlocked!=blocked)
567 {
570 }
571 if(blocked && frameBlocker.empty())frameBlocker=uiBlocker;
572 if(!collecting)return;
573 collecting=false;
574 for(auto& candidate:candidates)candidate.observation.wetGlassExcluded=wetGlassExcluded;
575 if(candidates.empty())return;
576 ProfileScope11 timing("Ad diagnostics queries");
577 std::stable_sort(candidates.begin(),candidates.end(),[](const Candidate& a,const Candidate& b){return a.estimatedPixels>b.estimatedPixels;});
578 if(blocked || !overlayFailure.empty() || !sceneCaptured || !weatherMeasured || uiRects.size()>64)
579 {
580 if(frameBlocker.empty())frameBlocker=!overlayFailure.empty() ? overlayFailure : !sceneCaptured ? "scene depth unavailable" :
581 !weatherMeasured ? "cloud/weather measurement unavailable" : "UI mask budget exceeded";
582 for(auto& candidate:candidates)
583 {
584 candidate.observation.measurable=false;candidate.observation.active=!blocked;
585 tracker.Observe(candidate.placement,candidate.observation);
586 }
587 ++dropped;return;
588 }
589 for(size_t i=MaximumCandidates;i<candidates.size();++i)
590 {candidates[i].observation.measurable=false;tracker.Observe(candidates[i].placement,candidates[i].observation);++dropped;}
592 unsigned replayDraws=0;
593 candidates.erase(std::remove_if(candidates.begin(),candidates.end(),[&](const Candidate& candidate)
594 {
595 const size_t draws=2+2*candidate.frontFacets.size()+2*candidate.angleFacets.size();
596 if(draws>MaximumReplayDraws-replayDraws)
597 {auto value=candidate.observation;value.measurable=false;tracker.Observe(candidate.placement,value);++dropped;return true;}
598 replayDraws+=unsigned(draws);return false;
599 }),candidates.end());
600 if(candidates.empty())return;
601 auto& frame=ring[nextFrame];frame.candidates.swap(candidates);candidates.clear();frame.seconds=sourceSeconds;
602 frame.sequence=++sequence;frame.eligibility=eligibilityGeneration;frame.samples=opaqueDepth.Description().SampleDesc.Count;
603 unsigned variant=0;while(variant<4 && (1u<<variant)!=frame.samples)++variant;
604 if(variant==4){frame.candidates.clear();++dropped;return;}
605 Restore restore;HRESULT hr=device.Context()->QueryInterface(IID_PPV_ARGS(&restore.context));
606 if(FAILED(hr)){++dropped;return;}
607 restore.context->SwapDeviceContextState(passState.Get(),&restore.previous);
608 auto* context=device.Context();Unbind(context);
609 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
610 if(!overlays.empty())
611 {
612 auto* target=glassTarget.Get();context->OMSetRenderTargets(1,&target,nullptr);
613 context->OMSetDepthStencilState(referenceDepth.Get(),0);context->OMSetBlendState(opacityBlend.Get(),nullptr,UINT_MAX);
614 for(const auto& overlay:overlays)
615 {
616 context->RSSetState(overlay.raster.Get());context->RSSetViewports(1,&overlay.viewport);
617 context->RSSetScissorRects(UINT(overlay.scissors.size()),overlay.scissors.data());
618 auto* buffer=overlay.buffer.Get();const UINT stride=32,offset=0;context->IASetVertexBuffers(0,1,&buffer,&stride,&offset);
619 hr=overlayPrograms[overlay.material].Bind(context,overlay.parameters);if(FAILED(hr))break;
620 context->Draw(overlay.count*3,overlay.first);
621 }
622 if(FAILED(hr))
623 {frame.candidates.clear();++dropped;frameBlocker="cockpit opacity replay failed";tracker.Interrupt(sourceSeconds,AdViewability::Reason::Unmeasured);return;}
624 }
625 context->RSSetState(raster.Get());context->RSSetViewports(1,&viewport);
626 context->OMSetBlendState(noColor.Get(),nullptr,UINT_MAX);
627 const int rectCount=int(uiRects.size());
628 for(size_t i=0;i<frame.candidates.size();++i)
629 {
630 auto& candidate=frame.candidates[i];auto& parameters=candidate.parameters;
631 parameters.Texture("adCloudOpacity",opacityView.Get());parameters.Texture("adGlassOpacity",glassView.Get());parameters.Set("adMaximumOpacity",AdViewability::Policy::MaximumCloudOpacity);
632 parameters.Set("adMinimumContrast",AdViewability::Policy::MinimumContrast);
633 parameters.Set("adMinimumContrastRetention",AdViewability::Policy::MinimumContrastRetention);
634 parameters.Set("adUiRectCount",rectCount);
635 if(rectCount)parameters.Set("adUiRects",uiRects.data(),size_t(rectCount)*sizeof(XMFLOAT4));
636 parameters.Set("adViewport",XMFLOAT4(viewport.TopLeftX,viewport.TopLeftY,viewport.Width,viewport.Height));
637 hr=candidate.patch->geometry.BindVertices(context,Layout(),0,false);if(FAILED(hr))break;
638 for(int metric=0;metric<6;++metric)
639 {
640 const bool reference=metric==0 || metric==4;
641 auto* color=sceneTarget.Get();context->OMSetRenderTargets(1,&color,reference ? nullptr : opaqueDepth.ReadView());
642 context->OMSetDepthStencilState(reference ? referenceDepth.Get() : visibleDepth.Get(),3);
643 parameters.Set("adMetric",metric);
644 hr=programs[candidate.material][variant].Bind(context,parameters);if(FAILED(hr))break;
645 context->Begin(frame.queries[i][metric].Get());
646 if(reference)context->Draw(UINT(candidate.patch->vertices.size()),0);
647 else for(const unsigned index:(metric==1 || metric==5) ? candidate.frontFacets : candidate.angleFacets)
648 {const auto& facet=candidate.patch->facets[index];context->Draw(facet.count,facet.first);}
649 context->End(frame.queries[i][metric].Get());
650 }
651 if(FAILED(hr))break;
652 }
653 if(FAILED(hr))
654 {
655 // Never reuse partially issued queries until the diagnostic is re-enabled.
656 frame.candidates.clear();++dropped;status="query draw failed";initializationFailed=true;
657 tracker.Interrupt(sourceSeconds,AdViewability::Reason::Unmeasured);return;
658 }
659 frame.pending=true;nextFrame=(nextFrame+1)%RingSize;
660 }
661 void AdDiagnostics11::Poll(RenderDevice& device,double now)
662 {
663 // Apply source frames in order, regardless of ring wrap/readiness.
664 for(unsigned attempt=0;attempt<RingSize;++attempt)
665 {
666 Frame* oldest=nullptr;for(auto& frame:ring)if(frame.pending && (!oldest || frame.sequence<oldest->sequence))oldest=&frame;
667 if(!oldest)return;
668 std::array<std::array<UINT64,6>,MaximumCandidates> counts{};
669 for(size_t i=0;i<oldest->candidates.size();++i)for(unsigned metric=0;metric<6;++metric)
670 {
671 const HRESULT hr=device.Context()->GetData(oldest->queries[i][metric].Get(),&counts[i][metric],sizeof(UINT64),D3D11_ASYNC_GETDATA_DONOTFLUSH);
672 if(hr==S_FALSE)return;
673 if(FAILED(hr)){oldest->pending=false;++dropped;tracker.Interrupt(now,AdViewability::Reason::Unmeasured);return;}
674 }
675 for(size_t i=0;i<oldest->candidates.size();++i)
676 {
677 auto& candidate=oldest->candidates[i];
678 if(candidate.slot<vehicles.size())
679 {if(candidate.generation!=vehicles[candidate.slot].generation)continue;}
680 else if(candidate.creativeLifetime.expired())continue;
681 auto& observation=candidate.observation;
682 const double referenceDivisor=oldest->samples*double(candidate.referenceScale)*candidate.referenceScale;
683 observation.referencePixels=double(counts[i][0])/referenceDivisor;
684 observation.visiblePixels=double(counts[i][1])/oldest->samples;
685 // Different reference translations can change edge sample rounding.
686 observation.referencePixels=(std::max)(observation.referencePixels,observation.visiblePixels);
687 observation.anglePixels=double(counts[i][2])/oldest->samples;
688 observation.clearPixels=double(counts[i][3])/oldest->samples;
689 observation.artworkReferencePixels=double(counts[i][4])/referenceDivisor;
690 observation.artworkVisiblePixels=double(counts[i][5])/oldest->samples;
691 observation.active=eligible && oldest->eligibility==eligibilityGeneration;
692 observation.measurable=now-oldest->seconds<=AdViewability::Policy::MaximumObservationGap;
693 tracker.Observe(candidate.placement,observation);
694 }
695 oldest->pending=false;oldest->candidates.clear();
696 }
697 }
698 void AdDiagnostics11::DrawOverlay(RenderFont* font,RenderSprite* sprite,unsigned width,unsigned height,std::vector<RECT>* drawnBounds)
699 {
700 if(!enabled || !overlayVisible || !font || !sprite)return;
701 ProfileScope11 timing("Ad diagnostics readout");
702 sprite->Begin(SpriteFlags::AlphaBlend);RECT rect{12,48,LONG(width)-12,(std::min)(LONG(height)-12,300L)};
703 // Cache text at the observation cadence, but measure its current bounds
704 // on every observation frame so the UI mask matches the actual draw.
706 {
707 std::ostringstream text;text<<"AD EXPOSURE: screen-percentage-seconds | 2025 attention diagnostics | local, not audited\n"
708 <<"Measure projected >=0.05% | standard: 50% visible, 1.5% screen, <=55deg, 1s | "<<(animatedInventory ? "170-230ms sampled" : "200ms")<<"\n"
709 <<status<<(frameBlocker.empty() ? "" : " | blocked: "+frameBlocker)<<" | dropped "<<dropped<<(logFailed ? " | LOG WRITE FAILED" : "")<<"\n";
710 text<<std::fixed<<std::setprecision(2);unsigned shown=0;
711 using Row=std::pair<const AdViewability::Placement,AdViewability::Record>;
712 std::vector<const Row*> rows;
713 for(const auto& item:tracker.Records())if(sourceSeconds-item.second.last.seconds<=2 && !item.second.last.backFacing)rows.push_back(&item);
714 std::stable_sort(rows.begin(),rows.end(),[](const Row* a,const Row* b)
715 {
716 const auto& x=a->second.last;const auto& y=b->second.last;
717 const bool xm=x.measurable && x.anglePixels>=0,ym=y.measurable && y.anglePixels>=0;
718 if(xm!=ym)return xm;
719 return x.referencePixels>y.referencePixels;
720 });
721 for(const auto* item:rows)
722 {
723 const auto& key=item->first;const auto& record=item->second;const auto& value=record.last;
724 if(++shown>8)break;
725 text<<key.entity<<"/"<<key.component<<"/"<<key.surface<<" "<<key.creative
726 <<" | SPS "<<record.screenPercentageSeconds<<" >=1.5% "<<record.aboveMinimumScreenPercentageSeconds
727 <<" qualified "<<record.qualifiedScreenPercentageSeconds<<" | standard "<<AdViewability::Name(record.reason);
728 if(value.sizeRejected)text<<" | below 0.05% measurement floor or empty | projected <="<<(value.screenPixels>0 ? value.referencePixels/value.screenPixels*100 : 0)<<"% (CPU); GPU visibility unmeasured";
729 else if(!value.measurable || value.anglePixels<0)
730 text<<" | GPU visibility unmeasured"<<(value.creativeHash ? "" : " (logo metadata pending/unsupported)");
731 else text<<" | screen "<<(value.screenPixels>0 ? value.visiblePixels/value.screenPixels*100 : 0)<<"%"
732 <<" visible "<<(value.referencePixels>0 ? value.visiblePixels/value.referencePixels*100 : 0)<<"%"
733 <<" readable "<<(value.referencePixels>0 ? value.clearPixels/value.referencePixels*100 : 0)<<"%"
734 <<" ink screen "<<(value.screenPixels>0 && value.artworkVisiblePixels>=0 ? value.artworkVisiblePixels/value.screenPixels*100 : 0)<<"%"
735 <<" angle-valid "<<(value.referencePixels>0 && value.anglePixels>=0 ? value.anglePixels/value.referencePixels*100 : 0)<<"%";
736 if(value.clipped)text<<" [partly off-screen]";
737 if(value.wetGlassExcluded)text<<" [wet-glass pixels excluded]";
738 if(key.kind==AdViewability::PlacementKind::BuildingSign)text<<" [sign frame "<<value.animationFrame+1<<"/"<<value.animationFrames<<"]";
739 text<<" main angles "<<value.yaw<<","<<value.pitch<<","<<value.roll
740 <<" | readable SPS "<<record.readableScreenPercentageSeconds
741 <<" | streak "<<record.continuousSeconds<<"s"
742 <<(record.qualified ? " [qualified once]" : "")<<"\n";
743 }
744 if(!shown)text<<(frameBlocker.empty() ?
745 "No logo measurement yet. A loaded overlay, authored logo UVs and a supported material draw are required.\n" :
746 "Measurement excluded by the blocker above; logo size/light/visibility have not been tested.\n");
748 }
749 const auto& content=overlayText;
750 if(drawnBounds)
751 {
752 RECT measured=rect,clipped{};
753 if(font->DrawTextA(nullptr,content.c_str(),-1,&measured,DT_LEFT|DT_TOP|DT_CALCRECT,0)>0 &&
754 IntersectRect(&clipped,&measured,&rect))drawnBounds->push_back(clipped);
755 }
756 font->DrawTextA(sprite,content.c_str(),-1,&rect,DT_LEFT|DT_TOP,0xffffff80);sprite->End();
757 }
758 void AdDiagnostics11::Checkpoint(double now,bool force)
759 {
760 if(!writer.joinable() || (!force && now-lastCheckpoint<5))return;lastCheckpoint=now;
761 ProfileScope11 timing("Ad diagnostics snapshot formatting",false);
762 const std::string snapshotUtc=Utc(UnixMilliseconds());const uint64_t snapshotId=++checkpointSequence;
763 const auto sourceUtc=[&](double seconds)
764 {return seconds<0 || sessionAnchorSeconds<0 ? std::string() : Utc(sessionAnchorUnixMs+uint64_t((std::max)(0.,seconds-sessionAnchorSeconds)*1000.));};
765 std::ostringstream out,summary;out<<std::setprecision(12);summary<<std::setprecision(12);
766 for(const auto& item:tracker.Records())
767 {
768 const auto& key=item.first;const auto& record=item.second;const auto& v=record.last;
769 out<<AdViewability::Policy::Version<<','<<now<<','<<int(key.kind)<<','<<key.entity<<','<<key.component<<','<<key.surface<<','<<CSV(key.creative)<<','
770 <<v.seconds<<','<<v.referencePixels<<','<<v.visiblePixels<<','<<v.clearPixels<<','<<v.screenPixels<<','<<v.yaw<<','<<v.pitch<<','<<v.roll<<','<<v.distanceKm<<','
771 <<CSV(AdViewability::Name(record.reason))<<','<<record.continuousSeconds<<','<<record.longestSeconds<<','<<record.eligibleSeconds<<','<<record.qualifiedSeconds<<','
772 <<record.qualified<<','<<record.observations<<','<<dropped<<','<<v.measurable<<','<<v.sizeRejected<<','
773 <<v.active<<','<<v.clipped<<','<<v.mirrored<<','<<v.anglePixels<<','<<v.backFacing<<','
774 <<v.projectionInvalid<<','<<v.creativeHash<<','<<v.sourceAlphaPixels<<','<<v.sourceMeanLuminance<<','<<v.sourceFillFraction<<','
775 <<v.artworkReferencePixels<<','<<v.artworkVisiblePixels<<','<<v.sourceWidth<<','<<v.sourceHeight<<','
776 <<v.sourceBounds[0]<<','<<v.sourceBounds[1]<<','<<v.sourceBounds[2]<<','<<v.sourceBounds[3]<<','
777 <<CSV(sessionId)<<','<<snapshotId<<','<<CSV(sessionStartUtc)<<','<<CSV(snapshotUtc)<<','<<CSV(force ? snapshotUtc : "")<<','<<force<<','
778 <<CSV(sourceUtc(record.firstVisibleSeconds))<<','<<CSV(sourceUtc(record.lastVisibleSeconds))<<','
779 <<record.measuredSeconds<<','<<record.visibleSeconds<<','<<record.screenPercentageSeconds<<','<<record.aboveMinimumScreenPercentageSeconds<<','
780 <<record.readableScreenPercentageSeconds<<','<<record.angleScreenPercentageSeconds<<','<<record.eligibleScreenPercentageSeconds<<','
781 <<record.qualifiedScreenPercentageSeconds<<','<<record.peakScreenPercentage<<','<<v.projectedWidthPixels<<','<<v.projectedHeightPixels<<','
782 <<AdViewability::Policy::MinimumMeasurementScreenFraction*100<<','<<v.animationFrame<<','<<v.animationFrames<<','
783 <<v.animationMeanLuminance<<','<<v.animationAlphaFraction<<','<<v.animationAnalyzedFraction<<','<<v.wetGlassExcluded<<'\n';
784 }
785 const auto summaries=tracker.Summaries();
786 const auto writeSummary=[&](const AdViewability::CreativeKey& key,const AdViewability::CreativeSummary& record)
787 {
788 summary<<AdViewability::Policy::Version<<','<<CSV(sessionId)<<','<<snapshotId<<','<<CSV(sessionStartUtc)<<','<<CSV(snapshotUtc)<<','
789 <<CSV(force ? snapshotUtc : "")<<','<<force<<','<<int(key.kind)<<','<<CSV(key.creative)<<','<<key.hash<<','
790 <<record.observedPlacements<<','<<record.visiblePlacements<<','<<record.qualifiedPlacements<<','
791 <<CSV(sourceUtc(record.firstVisibleSeconds))<<','<<CSV(sourceUtc(record.lastVisibleSeconds))<<','
792 <<record.measuredSeconds<<','<<record.visibleSeconds<<','<<record.screenPercentageSeconds<<','<<record.aboveMinimumScreenPercentageSeconds<<','
793 <<record.readableScreenPercentageSeconds<<','<<record.angleScreenPercentageSeconds<<','<<record.eligibleScreenPercentageSeconds<<','
794 <<record.qualifiedScreenPercentageSeconds<<','<<record.peakScreenPercentage<<','<<AdViewability::Policy::MinimumMeasurementScreenFraction*100<<'\n';
795 };
796 for(const auto& item:summaries)writeSummary(item.first,item.second);
797 // Preserve run dates/final status even if no creative was measurable.
798 if(summaries.empty())writeSummary({},{});
799 {std::lock_guard<std::mutex> lock(logMutex);if(snapshots.size()>=4){logFailed=true;return;}snapshots.push_back({out.str(),summary.str()});}
800 logReady.notify_one();
801 }
803 {
804 CreateDirectoryW(L"outputs",nullptr);FILE* file=_fsopen(logPath.c_str(),"w",_SH_DENYNO);
805 if(!file)logFailed=true;
806 else if(fputs("policy,snapshot_monotonic,kind,entity,component,surface,creative,source_monotonic,reference_pixels,visible_pixels,clear_pixels,screen_pixels,yaw,pitch,roll,distance_km,reason,continuous_seconds,longest_seconds,eligible_seconds,qualified_seconds,qualified_once,observations,dropped,measurable,size_rejected,active,clipped,mirrored,angle_pixels,back_facing,projection_invalid,creative_hash,source_alpha_pixels,source_mean_luminance,source_fill_fraction,artwork_reference_pixels,artwork_visible_pixels,source_width,source_height,source_u_min,source_v_min,source_u_max,source_v_max,session_id,snapshot_sequence,session_start_utc,snapshot_utc,session_end_utc,final_snapshot,first_visible_utc,last_visible_utc,measured_seconds,visible_seconds,screen_percentage_seconds,above_1_5_screen_percentage_seconds,readable_screen_percentage_seconds,angle_screen_percentage_seconds,eligible_screen_percentage_seconds,qualified_screen_percentage_seconds,peak_screen_percent,projected_width_pixels,projected_height_pixels,minimum_measurement_screen_percent,animation_frame,animation_frames,animation_mean_luminance,animation_alpha_fraction,animation_analyzed_fraction,wet_glass_excluded\n",file)<0)logFailed=true;
807 const std::string summaryPath=logPath.substr(0,logPath.size()-4)+"-summary.csv";
808 FILE* summary=_fsopen(summaryPath.c_str(),"w",_SH_DENYNO);
809 if(!summary)logFailed=true;
810 else if(fputs("policy,session_id,snapshot_sequence,session_start_utc,snapshot_utc,session_end_utc,final_snapshot,kind,creative,creative_hash,observed_placements,visible_placements,qualified_placements,first_visible_utc,last_visible_utc,measured_seconds,visible_seconds,screen_percentage_seconds,above_1_5_screen_percentage_seconds,readable_screen_percentage_seconds,angle_screen_percentage_seconds,eligible_screen_percentage_seconds,qualified_screen_percentage_seconds,peak_screen_percent,minimum_measurement_screen_percent\n",summary)<0)logFailed=true;
811 for(;;)
812 {
813 Snapshot snapshot;
814 {std::unique_lock<std::mutex> lock(logMutex);logReady.wait(lock,[&]{return logStop || !snapshots.empty();});
815 if(snapshots.empty() && logStop)break;snapshot=std::move(snapshots.front());snapshots.pop_front();}
816 const auto write=[&](FILE* target,const std::string& text)
817 {if(target && (fwrite(text.data(),1,text.size(),target)!=text.size() || fflush(target)!=0 || _commit(_fileno(target))!=0))logFailed=true;};
818 write(file,snapshot.placements);write(summary,snapshot.creatives);
819 }
820 if(file)fclose(file);
821 if(summary)fclose(summary);
822 }
824 {
825 if(!writer.joinable())return;
826 {std::lock_guard<std::mutex> lock(logMutex);logStop=true;}logReady.notify_one();writer.join();
827 }
828}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
void Interrupt(double now, Reason reason)
void Expire(double now)
bool Observe(const Placement &key, const Observation &value)
void RegisterSignDraw(RenderDevice &device, const AdViewability::Placement &placement, const CreativeMetadata *metadata, const std::weak_ptr< void > &lifetime, unsigned animationFrame, unsigned animationFrames, const AnimatedAdMetadata::Summary &average, Geometry11 &geometry, unsigned first, unsigned count, unsigned material, const DirectX::XMFLOAT4X4 &world, const DirectX::XMFLOAT4X4 &view, const DirectX::XMFLOAT4X4 &projection, float distanceKm)
AdViewability::Tracker tracker
static constexpr unsigned MaximumCreativePixels
std::vector< Candidate > candidates
Microsoft::WRL::ComPtr< ID3D11Device > metadataDevice
std::deque< Snapshot > snapshots
std::vector< VehicleIdentity > vehicles
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > opacityView
void DrawOverlay(RenderFont *font, RenderSprite *sprite, unsigned width, unsigned height, std::vector< RECT > *drawnBounds=nullptr)
void SyncPlacement(unsigned slot, uint64_t entity, const std::string &creative)
Microsoft::WRL::ComPtr< ID3D11Device > native
Microsoft::WRL::ComPtr< ID3D11BlendState > opacityBlend
Microsoft::WRL::ComPtr< ID3D11Texture2D > opacityTexture
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > visibleDepth
Microsoft::WRL::ComPtr< ID3D11RenderTargetView > sceneTarget
void RegisterDraw(RenderDevice &device, const AdViewability::Placement &placement, unsigned slot, Geometry11 &geometry, unsigned first, unsigned count, unsigned material, const DirectX::XMFLOAT4X4 &world, const DirectX::XMFLOAT4X4 &view, const DirectX::XMFLOAT4X4 &projection, float distanceKm)
void WetGlassResult(HRESULT result)
std::vector< std::shared_ptr< Patch > > & Mesh(RenderDevice &device, Geometry11 &geometry, unsigned first, unsigned count, const DirectX::XMFLOAT4 &bounds, unsigned frontConvention=0)
std::deque< CachedCreative > creatives
HRESULT Initialize(RenderDevice &device)
void BeginFrame(RenderDevice &device, double now, bool eligible, const char *blocker=nullptr)
void RegisterOverlayDraw(RenderDevice &device, Geometry11 &geometry, unsigned first, unsigned count, unsigned material)
void Checkpoint(double now, bool force=false)
Microsoft::WRL::ComPtr< ID3D11RasterizerState > raster
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > referenceDepth
std::condition_variable logReady
Microsoft::WRL::ComPtr< ID3D11RenderTargetView > glassTarget
std::array< std::array< Program11, 4 >, 4 > programs
static constexpr unsigned RingSize
AdCreativeMetadata CreativeMetadata
std::array< Frame, RingSize > ring
void RegisterPreparedDraw(RenderDevice &device, const AdViewability::Placement &placement, unsigned slot, const CreativeMetadata *metadata, const std::weak_ptr< void > &lifetime, unsigned animationFrame, unsigned animationFrames, const AnimatedAdMetadata::Summary &average, Geometry11 &geometry, unsigned first, unsigned count, unsigned program, const DirectX::XMFLOAT4X4 &world, const DirectX::XMFLOAT4X4 &view, const DirectX::XMFLOAT4X4 &projection, float distanceKm)
static constexpr unsigned MaximumCandidates
Microsoft::WRL::ComPtr< ID3D11Texture2D > glassTexture
std::deque< CachedMesh > meshes
std::array< Program11, 3 > overlayPrograms
void Poll(RenderDevice &device, double now)
void FinishScene(RenderDevice &device, bool weatherMeasured, const std::vector< DirectX::XMFLOAT4 > &uiRects, const char *uiBlocker=nullptr)
const CreativeMetadata * PrepareCreative(RenderDevice &device, ID3D11ShaderResourceView *view)
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > glassView
std::atomic< bool > logFailed
HRESULT CaptureScene(RenderDevice &device)
Microsoft::WRL::ComPtr< ID3D11BlendState > noColor
std::vector< OverlayDraw > overlays
static constexpr unsigned MaximumCreatives
Microsoft::WRL::ComPtr< ID3D11RenderTargetView > opacityTarget
Microsoft::WRL::ComPtr< ID3DDeviceContextState > passState
const D3D11_VIEWPORT & Viewport() const
Materials11 & Materials()
HRESULT NativeBuffer(ID3D11DeviceContext *context, ID3D11Buffer **result)
uint64_t Revision() const
Definition Geometry11.h:41
const std::vector< uint8_t > & Bytes() const
Definition Geometry11.h:37
Parameters11 & Values()
Definition Materials11.h:14
void Set(const std::string &name, const void *data, size_t bytes)
Definition Program11.cpp:45
void Texture(const std::string &name, ID3D11ShaderResourceView *value)
Definition Program11.cpp:55
DrawContext11 & Draws()
ID3D11DeviceContext * Context()
INT DrawTextA(RenderSprite *sprite, const char *text, INT count, RECT *rectangle, DWORD flags, PackedColor color)
HRESULT Begin(DWORD flags)
ID3D11Texture2D * Texture() const
Definition Device11.h:17
const D3D11_TEXTURE2D_DESC & Description() const
Definition Device11.h:22
HRESULT Create(ID3D11Device *device, UINT width, UINT height, DXGI_SAMPLE_DESC samples)
Definition Device11.cpp:20
char area[3]
Definition globals.cpp:87
const char * Name(Reason reason)
std::array< Panel, Count > Layout
Definition DDS.h:24
float Length(const Vector &a)
Definition Math11.h:18
Vector Normalize(const Vector &a)
Definition Math11.h:21
Vector Cross(const Vector &a, const Vector &b)
Definition Math11.h:19
float Dot(const Vector &a, const Vector &b)
Definition Math11.h:15
constexpr DWORD AlphaBlend
std::vector< char > ReadShaderBytecode11(const std::filesystem::path &path, HMODULE resourceModule=nullptr)
Model.
std::array< float, 4 > sourceBounds
static constexpr double PollSeconds
static constexpr float MinimumContrastRetention
static constexpr double MinimumMeasurementScreenFraction
static constexpr unsigned Version
static constexpr float MaximumCloudOpacity
static constexpr double MaximumObservationGap
static constexpr double MaximumAngleDegrees
static constexpr float MinimumContrast
Microsoft::WRL::ComPtr< ID3D11Texture2D > staging
AdViewability::Observation observation
std::vector< Candidate > candidates
std::array< std::array< Query, 6 >, MaximumCandidates > queries
Microsoft::WRL::ComPtr< ID3D11Buffer > buffer
Microsoft::WRL::ComPtr< ID3D11RasterizerState > raster
D3D11_BLEND_DESC blend
std::vector< D3D11_INPUT_ELEMENT_DESC > Elements() const