1 /*************************************************************************
2  *
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * Copyright 2000, 2010 Oracle and/or its affiliates.
6  *
7  * OpenOffice.org - a multi-platform office productivity suite
8  *
9  * This file is part of OpenOffice.org.
10  *
11  * OpenOffice.org is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License version 3
13  * only, as published by the Free Software Foundation.
14  *
15  * OpenOffice.org is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Lesser General Public License version 3 for more details
19  * (a copy is included in the LICENSE file that accompanied this code).
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * version 3 along with OpenOffice.org.  If not, see
23  * <http://www.openoffice.org/license.html>
24  * for a copy of the LGPLv3 License.
25  *
26  ************************************************************************/
27 
28 // MARKER(update_precomp.py): autogen include statement, do not remove
29 #include "precompiled_drawinglayer.hxx"
30 
31 #include <drawinglayer/processor3d/zbufferprocessor3d.hxx>
32 #include <basegfx/raster/bpixelraster.hxx>
33 #include <vcl/bmpacc.hxx>
34 #include <basegfx/raster/rasterconvert3d.hxx>
35 #include <basegfx/raster/bzpixelraster.hxx>
36 #include <drawinglayer/attribute/materialattribute3d.hxx>
37 #include <drawinglayer/texture/texture.hxx>
38 #include <drawinglayer/primitive3d/drawinglayer_primitivetypes3d.hxx>
39 #include <drawinglayer/primitive3d/textureprimitive3d.hxx>
40 #include <drawinglayer/primitive3d/polygonprimitive3d.hxx>
41 #include <drawinglayer/primitive3d/polypolygonprimitive3d.hxx>
42 #include <drawinglayer/geometry/viewinformation2d.hxx>
43 #include <basegfx/polygon/b3dpolygontools.hxx>
44 #include <basegfx/polygon/b3dpolypolygontools.hxx>
45 #include <drawinglayer/attribute/sdrlightingattribute3d.hxx>
46 
47 //////////////////////////////////////////////////////////////////////////////
48 
49 using namespace com::sun::star;
50 
51 //////////////////////////////////////////////////////////////////////////////
52 
53 namespace
54 {
55 	BitmapEx BPixelRasterToBitmapEx(const basegfx::BPixelRaster& rRaster, sal_uInt16 mnAntiAlialize)
56 	{
57 		BitmapEx aRetval;
58 		const sal_uInt32 nWidth(mnAntiAlialize ? rRaster.getWidth()/mnAntiAlialize : rRaster.getWidth());
59 		const sal_uInt32 nHeight(mnAntiAlialize ? rRaster.getHeight()/mnAntiAlialize : rRaster.getHeight());
60 
61 		if(nWidth && nHeight)
62 		{
63 			const Size aDestSize(nWidth, nHeight);
64 			sal_uInt8 nInitAlpha(255);
65 			Bitmap aContent(aDestSize, 24);
66 			AlphaMask aAlpha(aDestSize, &nInitAlpha);
67 			BitmapWriteAccess* pContent = aContent.AcquireWriteAccess();
68 			BitmapWriteAccess* pAlpha = aAlpha.AcquireWriteAccess();
69 
70 			if(pContent && pAlpha)
71 			{
72 				if(mnAntiAlialize)
73 				{
74 					const sal_uInt16 nDivisor(mnAntiAlialize * mnAntiAlialize);
75 
76 					for(sal_uInt32 y(0L); y < nHeight; y++)
77 					{
78 						for(sal_uInt32 x(0L); x < nWidth; x++)
79 						{
80 							sal_uInt16 nRed(0);
81 							sal_uInt16 nGreen(0);
82 							sal_uInt16 nBlue(0);
83 							sal_uInt16 nOpacity(0);
84 							sal_uInt32 nIndex(rRaster.getIndexFromXY(x * mnAntiAlialize, y * mnAntiAlialize));
85 
86 							for(sal_uInt32 c(0); c < mnAntiAlialize; c++)
87 							{
88 								for(sal_uInt32 d(0); d < mnAntiAlialize; d++)
89 								{
90 									const basegfx::BPixel& rPixel(rRaster.getBPixel(nIndex++));
91 									nRed = nRed + rPixel.getRed();
92 									nGreen = nGreen + rPixel.getGreen();
93 									nBlue = nBlue + rPixel.getBlue();
94 									nOpacity = nOpacity + rPixel.getOpacity();
95 								}
96 
97 								nIndex += rRaster.getWidth() - mnAntiAlialize;
98 							}
99 
100 							nOpacity = nOpacity / nDivisor;
101 
102 							if(nOpacity)
103 							{
104 								pContent->SetPixel(y, x, BitmapColor(
105 									(sal_uInt8)(nRed / nDivisor),
106 									(sal_uInt8)(nGreen / nDivisor),
107 									(sal_uInt8)(nBlue / nDivisor)));
108 								pAlpha->SetPixel(y, x, BitmapColor(255 - (sal_uInt8)nOpacity));
109 							}
110 						}
111 					}
112 				}
113 				else
114 				{
115 					sal_uInt32 nIndex(0L);
116 
117 					for(sal_uInt32 y(0L); y < nHeight; y++)
118 					{
119 						for(sal_uInt32 x(0L); x < nWidth; x++)
120 						{
121 							const basegfx::BPixel& rPixel(rRaster.getBPixel(nIndex++));
122 
123 							if(rPixel.getOpacity())
124 							{
125 								pContent->SetPixel(y, x, BitmapColor(rPixel.getRed(), rPixel.getGreen(), rPixel.getBlue()));
126 								pAlpha->SetPixel(y, x, BitmapColor(255 - rPixel.getOpacity()));
127 							}
128 						}
129 					}
130 				}
131 
132 				delete pContent;
133 				delete pAlpha;
134 			}
135 
136 			aRetval = BitmapEx(aContent, aAlpha);
137 
138 			// #i101811# set PrefMapMode and PrefSize at newly created Bitmap
139 			aRetval.SetPrefMapMode(MAP_100TH_MM);
140 			aRetval.SetPrefSize(Size(nWidth, nHeight));
141 		}
142 
143 		return aRetval;
144 	}
145 } // end of anonymous namespace
146 
147 //////////////////////////////////////////////////////////////////////////////
148 
149 class ZBufferRasterConverter3D : public basegfx::RasterConverter3D
150 {
151 private:
152     const drawinglayer::processor3d::DefaultProcessor3D&	mrProcessor;
153     basegfx::BZPixelRaster&								    mrBuffer;
154 
155     // interpolators for a single line span
156     basegfx::ip_single										maIntZ;
157     basegfx::ip_triple										maIntColor;
158     basegfx::ip_triple										maIntNormal;
159     basegfx::ip_double										maIntTexture;
160     basegfx::ip_triple										maIntInvTexture;
161 
162     // current material to use for ratsreconversion
163     const drawinglayer::attribute::MaterialAttribute3D*     mpCurrentMaterial;
164 
165     // bitfield
166     // some boolean flags for line span interpolator usages
167     unsigned												mbModifyColor : 1;
168     unsigned												mbUseTex : 1;
169     unsigned												mbHasTexCoor : 1;
170     unsigned												mbHasInvTexCoor : 1;
171     unsigned												mbUseNrm : 1;
172     unsigned												mbUseCol : 1;
173 
174     void getTextureCoor(basegfx::B2DPoint& rTarget) const
175     {
176 	    if(mbHasTexCoor)
177 	    {
178 		    rTarget.setX(maIntTexture.getX().getVal());
179 		    rTarget.setY(maIntTexture.getY().getVal());
180 	    }
181 	    else if(mbHasInvTexCoor)
182 	    {
183 		    const double fZFactor(maIntInvTexture.getZ().getVal());
184             const double fInvZFactor(basegfx::fTools::equalZero(fZFactor) ? 1.0 : 1.0 / fZFactor);
185 		    rTarget.setX(maIntInvTexture.getX().getVal() * fInvZFactor);
186 		    rTarget.setY(maIntInvTexture.getY().getVal() * fInvZFactor);
187 	    }
188     }
189 
190     void incrementLineSpanInterpolators(double fStep)
191     {
192 	    maIntZ.increment(fStep);
193 
194 	    if(mbUseTex)
195 	    {
196 		    if(mbHasTexCoor)
197 		    {
198 			    maIntTexture.increment(fStep);
199 		    }
200 		    else if(mbHasInvTexCoor)
201 		    {
202 			    maIntInvTexture.increment(fStep);
203 		    }
204 	    }
205 
206 	    if(mbUseNrm)
207 	    {
208 		    maIntNormal.increment(fStep);
209 	    }
210 
211 	    if(mbUseCol)
212 	    {
213 		    maIntColor.increment(fStep);
214 	    }
215     }
216 
217     double decideColorAndOpacity(basegfx::BColor& rColor)
218     {
219         // init values with full opacity and material color
220         OSL_ENSURE(0 != mpCurrentMaterial, "CurrentMaterial not set (!)");
221         double fOpacity(1.0);
222         rColor = mpCurrentMaterial->getColor();
223 
224         if(mbUseTex)
225         {
226             basegfx::B2DPoint aTexCoor(0.0, 0.0);
227 	        getTextureCoor(aTexCoor);
228 
229 	        if(mrProcessor.getGeoTexSvx().get())
230 	        {
231 		        // calc color in spot. This may also set to invisible already when
232 		        // e.g. bitmap textures have transparent parts
233 		        mrProcessor.getGeoTexSvx()->modifyBColor(aTexCoor, rColor, fOpacity);
234 	        }
235 
236 	        if(basegfx::fTools::more(fOpacity, 0.0) && mrProcessor.getTransparenceGeoTexSvx().get())
237 	        {
238 		        // calc opacity. Object has a 2nd texture, a transparence texture
239 		        mrProcessor.getTransparenceGeoTexSvx()->modifyOpacity(aTexCoor, fOpacity);
240 	        }
241         }
242 
243         if(basegfx::fTools::more(fOpacity, 0.0))
244         {
245 	        if(mrProcessor.getGeoTexSvx().get())
246 	        {
247 		        if(mbUseNrm)
248 		        {
249 			        // blend texture with phong
250 			        rColor = mrProcessor.getSdrLightingAttribute().solveColorModel(
251 				        basegfx::B3DVector(maIntNormal.getX().getVal(), maIntNormal.getY().getVal(), maIntNormal.getZ().getVal()),
252 				        rColor,
253 				        mpCurrentMaterial->getSpecular(),
254 				        mpCurrentMaterial->getEmission(),
255 				        mpCurrentMaterial->getSpecularIntensity());
256 		        }
257 		        else if(mbUseCol)
258 		        {
259 			        // blend texture with gouraud
260 			        basegfx::BColor aBlendColor(maIntColor.getX().getVal(), maIntColor.getY().getVal(), maIntColor.getZ().getVal());
261 			        rColor *= aBlendColor;
262 		        }
263 		        else if(mrProcessor.getModulate())
264 		        {
265 			        // blend texture with single material color
266 			        rColor *= mpCurrentMaterial->getColor();
267 		        }
268 	        }
269 	        else
270 	        {
271 		        if(mbUseNrm)
272 		        {
273 			        // modify color with phong
274 			        rColor = mrProcessor.getSdrLightingAttribute().solveColorModel(
275 				        basegfx::B3DVector(maIntNormal.getX().getVal(), maIntNormal.getY().getVal(), maIntNormal.getZ().getVal()),
276 				        rColor,
277 				        mpCurrentMaterial->getSpecular(),
278 				        mpCurrentMaterial->getEmission(),
279 				        mpCurrentMaterial->getSpecularIntensity());
280 		        }
281 		        else if(mbUseCol)
282 		        {
283 			        // modify color with gouraud
284 			        rColor.setRed(maIntColor.getX().getVal());
285 			        rColor.setGreen(maIntColor.getY().getVal());
286 			        rColor.setBlue(maIntColor.getZ().getVal());
287 		        }
288 	        }
289 
290 	        if(mbModifyColor)
291 	        {
292 		        rColor = mrProcessor.getBColorModifierStack().getModifiedColor(rColor);
293 	        }
294         }
295 
296         return fOpacity;
297     }
298 
299     void setupLineSpanInterpolators(const basegfx::RasterConversionLineEntry3D& rA, const basegfx::RasterConversionLineEntry3D& rB)
300     {
301         // get inverse XDelta
302         const double xInvDelta(1.0 / (rB.getX().getVal() - rA.getX().getVal()));
303 
304         // prepare Z-interpolator
305         const double fZA(rA.getZ().getVal());
306         const double fZB(rB.getZ().getVal());
307         maIntZ = basegfx::ip_single(fZA, (fZB - fZA) * xInvDelta);
308 
309         // get bools and init other interpolators on demand accordingly
310         mbModifyColor = mrProcessor.getBColorModifierStack().count();
311         mbHasTexCoor = SCANLINE_EMPTY_INDEX != rA.getTextureIndex() && SCANLINE_EMPTY_INDEX != rB.getTextureIndex();
312         mbHasInvTexCoor = SCANLINE_EMPTY_INDEX != rA.getInverseTextureIndex() && SCANLINE_EMPTY_INDEX != rB.getInverseTextureIndex();
313         const bool bTextureActive(mrProcessor.getGeoTexSvx().get() || mrProcessor.getTransparenceGeoTexSvx().get());
314         mbUseTex = bTextureActive && (mbHasTexCoor || mbHasInvTexCoor || mrProcessor.getSimpleTextureActive());
315         const bool bUseColorTex(mbUseTex && mrProcessor.getGeoTexSvx().get());
316         const bool bNeedNrmOrCol(!bUseColorTex || (bUseColorTex && mrProcessor.getModulate()));
317         mbUseNrm = bNeedNrmOrCol && SCANLINE_EMPTY_INDEX != rA.getNormalIndex() && SCANLINE_EMPTY_INDEX != rB.getNormalIndex();
318         mbUseCol = !mbUseNrm && bNeedNrmOrCol && SCANLINE_EMPTY_INDEX != rA.getColorIndex() && SCANLINE_EMPTY_INDEX != rB.getColorIndex();
319 
320         if(mbUseTex)
321         {
322 	        if(mbHasTexCoor)
323 	        {
324                 const basegfx::ip_double& rTA(getTextureInterpolators()[rA.getTextureIndex()]);
325 		        const basegfx::ip_double& rTB(getTextureInterpolators()[rB.getTextureIndex()]);
326 		        maIntTexture = basegfx::ip_double(
327 			        rTA.getX().getVal(), (rTB.getX().getVal() - rTA.getX().getVal()) * xInvDelta,
328 			        rTA.getY().getVal(), (rTB.getY().getVal() - rTA.getY().getVal()) * xInvDelta);
329 	        }
330 	        else if(mbHasInvTexCoor)
331 	        {
332 		        const basegfx::ip_triple& rITA(getInverseTextureInterpolators()[rA.getInverseTextureIndex()]);
333 		        const basegfx::ip_triple& rITB(getInverseTextureInterpolators()[rB.getInverseTextureIndex()]);
334 		        maIntInvTexture = basegfx::ip_triple(
335 			        rITA.getX().getVal(), (rITB.getX().getVal() - rITA.getX().getVal()) * xInvDelta,
336 			        rITA.getY().getVal(), (rITB.getY().getVal() - rITA.getY().getVal()) * xInvDelta,
337 			        rITA.getZ().getVal(), (rITB.getZ().getVal() - rITA.getZ().getVal()) * xInvDelta);
338 	        }
339         }
340 
341         if(mbUseNrm)
342         {
343 	        const basegfx::ip_triple& rNA(getNormalInterpolators()[rA.getNormalIndex()]);
344 	        const basegfx::ip_triple& rNB(getNormalInterpolators()[rB.getNormalIndex()]);
345 	        maIntNormal = basegfx::ip_triple(
346 		        rNA.getX().getVal(), (rNB.getX().getVal() - rNA.getX().getVal()) * xInvDelta,
347 		        rNA.getY().getVal(), (rNB.getY().getVal() - rNA.getY().getVal()) * xInvDelta,
348 		        rNA.getZ().getVal(), (rNB.getZ().getVal() - rNA.getZ().getVal()) * xInvDelta);
349         }
350 
351         if(mbUseCol)
352         {
353 	        const basegfx::ip_triple& rCA(getColorInterpolators()[rA.getColorIndex()]);
354 	        const basegfx::ip_triple& rCB(getColorInterpolators()[rB.getColorIndex()]);
355 	        maIntColor = basegfx::ip_triple(
356 		        rCA.getX().getVal(), (rCB.getX().getVal() - rCA.getX().getVal()) * xInvDelta,
357 		        rCA.getY().getVal(), (rCB.getY().getVal() - rCA.getY().getVal()) * xInvDelta,
358 		        rCA.getZ().getVal(), (rCB.getZ().getVal() - rCA.getZ().getVal()) * xInvDelta);
359         }
360     }
361 
362     virtual void processLineSpan(const basegfx::RasterConversionLineEntry3D& rA, const basegfx::RasterConversionLineEntry3D& rB, sal_Int32 nLine, sal_uInt32 nSpanCount);
363 
364 public:
365     ZBufferRasterConverter3D(basegfx::BZPixelRaster& rBuffer, const drawinglayer::processor3d::ZBufferProcessor3D& rProcessor)
366     :   basegfx::RasterConverter3D(),
367         mrProcessor(rProcessor),
368         mrBuffer(rBuffer),
369 	    maIntZ(),
370 	    maIntColor(),
371 	    maIntNormal(),
372 	    maIntTexture(),
373 	    maIntInvTexture(),
374         mpCurrentMaterial(0),
375 	    mbModifyColor(false),
376 	    mbUseTex(false),
377 	    mbHasTexCoor(false),
378 	    mbUseNrm(false),
379 	    mbUseCol(false)
380     {}
381 
382     void setCurrentMaterial(const drawinglayer::attribute::MaterialAttribute3D& rMaterial)
383 	{
384         mpCurrentMaterial = &rMaterial;
385     }
386 };
387 
388 void ZBufferRasterConverter3D::processLineSpan(const basegfx::RasterConversionLineEntry3D& rA, const basegfx::RasterConversionLineEntry3D& rB, sal_Int32 nLine, sal_uInt32 nSpanCount)
389 {
390     if(!(nSpanCount & 0x0001))
391     {
392 	    if(nLine >= 0 && nLine < (sal_Int32)mrBuffer.getHeight())
393 	    {
394 			sal_uInt32 nXA(::std::min(mrBuffer.getWidth(), (sal_uInt32)::std::max((sal_Int32)0, basegfx::fround(rA.getX().getVal()))));
395 			const sal_uInt32 nXB(::std::min(mrBuffer.getWidth(), (sal_uInt32)::std::max((sal_Int32)0, basegfx::fround(rB.getX().getVal()))));
396 
397 	        if(nXA < nXB)
398 	        {
399 		        // prepare the span interpolators
400 		        setupLineSpanInterpolators(rA, rB);
401 
402 		        // bring span interpolators to start condition by incrementing with the possible difference of
403 		        // clamped and non-clamped XStart. Interpolators are setup relying on double precision
404 		        // X-values, so that difference is the correct value to compensate for possible clampings
405 		        incrementLineSpanInterpolators(static_cast<double>(nXA) - rA.getX().getVal());
406 
407 		        // prepare scanline index
408 		        sal_uInt32 nScanlineIndex(mrBuffer.getIndexFromXY(nXA, static_cast<sal_uInt32>(nLine)));
409                 basegfx::BColor aNewColor;
410 
411 		        while(nXA < nXB)
412 		        {
413 			        // early-test Z values if we need to do anything at all
414 					const double fNewZ(::std::max(0.0, ::std::min((double)0xffff, maIntZ.getVal())));
415 			        const sal_uInt16 nNewZ(static_cast< sal_uInt16 >(fNewZ));
416 					sal_uInt16& rOldZ(mrBuffer.getZ(nScanlineIndex));
417 
418 			        if(nNewZ > rOldZ)
419 			        {
420 				        // detect color and opacity for this pixel
421 						const sal_uInt16 nOpacity(::std::max((sal_Int16)0, static_cast< sal_Int16 >(decideColorAndOpacity(aNewColor) * 255.0)));
422 
423 						if(nOpacity > 0)
424 						{
425 							// avoid color overrun
426 							aNewColor.clamp();
427 
428 							if(nOpacity >= 0x00ff)
429 							{
430 								// full opacity (not transparent), set z and color
431 								rOldZ = nNewZ;
432 								mrBuffer.getBPixel(nScanlineIndex) = basegfx::BPixel(aNewColor, 0xff);
433 							}
434 							else
435 							{
436                                 basegfx::BPixel& rDest = mrBuffer.getBPixel(nScanlineIndex);
437 
438                                 if(rDest.getOpacity())
439                                 {
440                                     // mix new color by using
441                                     // color' = color * (1 - opacity) + newcolor * opacity
442 									const sal_uInt16 nTransparence(0x0100 - nOpacity);
443 									rDest.setRed((sal_uInt8)(((rDest.getRed() * nTransparence) + ((sal_uInt16)(255.0 * aNewColor.getRed()) * nOpacity)) >> 8));
444 									rDest.setGreen((sal_uInt8)(((rDest.getGreen() * nTransparence) + ((sal_uInt16)(255.0 * aNewColor.getGreen()) * nOpacity)) >> 8));
445 									rDest.setBlue((sal_uInt8)(((rDest.getBlue() * nTransparence) + ((sal_uInt16)(255.0 * aNewColor.getBlue()) * nOpacity)) >> 8));
446 
447                                     if(0xff != rDest.getOpacity())
448                                     {
449                                         // both are transparent, mix new opacity by using
450                                         // opacity = newopacity * (1 - oldopacity) + oldopacity
451                                         rDest.setOpacity(((sal_uInt8)((nOpacity * (0x0100 - rDest.getOpacity())) >> 8)) + rDest.getOpacity());
452                                     }
453                                 }
454                                 else
455                                 {
456 									// dest is unused, set color
457 									rDest = basegfx::BPixel(aNewColor, (sal_uInt8)nOpacity);
458                                 }
459 							}
460 						}
461 			        }
462 
463 			        // increments
464 			        nScanlineIndex++;
465 			        nXA++;
466 			        incrementLineSpanInterpolators(1.0);
467 		        }
468 	        }
469         }
470     }
471 }
472 
473 //////////////////////////////////////////////////////////////////////////////
474 // helper class to buffer output for transparent rasterprimitives (filled areas
475 // and lines) until the end of processing. To ensure correct transparent
476 // visualisation, ZBuffers require to not set Z and to mix with the transparent
477 // color. If transparent rasterprimitives overlap, it gets necessary to
478 // paint transparent rasterprimitives from back to front to ensure that the
479 // mixing happens from back to front. For that purpose, transparent
480 // rasterprimitives are held in this class during the processing run, remember
481 // all data and will be rendered
482 
483 class RasterPrimitive3D
484 {
485 private:
486     boost::shared_ptr< drawinglayer::texture::GeoTexSvx >     mpGeoTexSvx;
487     boost::shared_ptr< drawinglayer::texture::GeoTexSvx >     mpTransparenceGeoTexSvx;
488     drawinglayer::attribute::MaterialAttribute3D              maMaterial;
489     basegfx::B3DPolyPolygon                                   maPolyPolygon;
490     double                                                    mfCenterZ;
491 
492     // bitfield
493     bool                                                      mbModulate : 1;
494     bool                                                      mbFilter : 1;
495     bool                                                      mbSimpleTextureActive : 1;
496     bool                                                      mbIsLine : 1;
497 
498 public:
499     RasterPrimitive3D(
500         const boost::shared_ptr< drawinglayer::texture::GeoTexSvx >& pGeoTexSvx,
501         const boost::shared_ptr< drawinglayer::texture::GeoTexSvx >& pTransparenceGeoTexSvx,
502         const drawinglayer::attribute::MaterialAttribute3D& rMaterial,
503         const basegfx::B3DPolyPolygon& rPolyPolygon,
504         bool bModulate,
505         bool bFilter,
506         bool bSimpleTextureActive,
507         bool bIsLine)
508     :   mpGeoTexSvx(pGeoTexSvx),
509         mpTransparenceGeoTexSvx(pTransparenceGeoTexSvx),
510         maMaterial(rMaterial),
511         maPolyPolygon(rPolyPolygon),
512         mfCenterZ(basegfx::tools::getRange(rPolyPolygon).getCenter().getZ()),
513         mbModulate(bModulate),
514         mbFilter(bFilter),
515         mbSimpleTextureActive(bSimpleTextureActive),
516         mbIsLine(bIsLine)
517     {
518     }
519 
520 	RasterPrimitive3D& operator=(const RasterPrimitive3D& rComp)
521 	{
522         mpGeoTexSvx = rComp.mpGeoTexSvx;
523         mpTransparenceGeoTexSvx = rComp.mpTransparenceGeoTexSvx;
524         maMaterial = rComp.maMaterial;
525         maPolyPolygon = rComp.maPolyPolygon;
526         mfCenterZ = rComp.mfCenterZ;
527         mbModulate = rComp.mbModulate;
528         mbFilter = rComp.mbFilter;
529         mbSimpleTextureActive = rComp.mbSimpleTextureActive;
530         mbIsLine = rComp.mbIsLine;
531 
532         return *this;
533     }
534 
535 	bool operator<(const RasterPrimitive3D& rComp) const
536 	{
537         return mfCenterZ < rComp.mfCenterZ;
538 	}
539 
540     const boost::shared_ptr< drawinglayer::texture::GeoTexSvx >& getGeoTexSvx() const { return mpGeoTexSvx; }
541     const boost::shared_ptr< drawinglayer::texture::GeoTexSvx >& getTransparenceGeoTexSvx() const { return mpTransparenceGeoTexSvx; }
542     const drawinglayer::attribute::MaterialAttribute3D& getMaterial() const { return maMaterial; }
543     const basegfx::B3DPolyPolygon& getPolyPolygon() const { return maPolyPolygon; }
544     bool getModulate() const { return mbModulate; }
545     bool getFilter() const { return mbFilter; }
546     bool getSimpleTextureActive() const { return mbSimpleTextureActive; }
547     bool getIsLine() const { return mbIsLine; }
548 };
549 
550 //////////////////////////////////////////////////////////////////////////////
551 
552 namespace drawinglayer
553 {
554 	namespace processor3d
555 	{
556 		void ZBufferProcessor3D::rasterconvertB3DPolygon(const attribute::MaterialAttribute3D& rMaterial, const basegfx::B3DPolygon& rHairline) const
557 		{
558 			if(mpBZPixelRaster)
559 			{
560                 if(getTransparenceCounter())
561                 {
562                     // transparent output; record for later sorting and painting from
563                     // back to front
564                     if(!mpRasterPrimitive3Ds)
565                     {
566                         const_cast< ZBufferProcessor3D* >(this)->mpRasterPrimitive3Ds = new std::vector< RasterPrimitive3D >;
567                     }
568 
569                     mpRasterPrimitive3Ds->push_back(RasterPrimitive3D(
570                         getGeoTexSvx(),
571                         getTransparenceGeoTexSvx(),
572                         rMaterial,
573                         basegfx::B3DPolyPolygon(rHairline),
574                         getModulate(),
575                         getFilter(),
576                         getSimpleTextureActive(),
577                         true));
578                 }
579                 else
580                 {
581                     // do rasterconversion
582                     mpZBufferRasterConverter3D->setCurrentMaterial(rMaterial);
583 
584 				    if(mnAntiAlialize > 1)
585 				    {
586                         const bool bForceLineSnap(getOptionsDrawinglayer().IsAntiAliasing() && getOptionsDrawinglayer().IsSnapHorVerLinesToDiscrete());
587 
588 					    if(bForceLineSnap)
589 					    {
590 						    basegfx::B3DHomMatrix aTransform;
591 						    basegfx::B3DPolygon aSnappedHairline(rHairline);
592 						    const double fScaleDown(1.0 / mnAntiAlialize);
593 						    const double fScaleUp(mnAntiAlialize);
594 
595 						    // take oversampling out
596 						    aTransform.scale(fScaleDown, fScaleDown, 1.0);
597 						    aSnappedHairline.transform(aTransform);
598 
599 						    // snap to integer
600 						    aSnappedHairline = basegfx::tools::snapPointsOfHorizontalOrVerticalEdges(aSnappedHairline);
601 
602 						    // add oversampling again
603 						    aTransform.identity();
604 						    aTransform.scale(fScaleUp, fScaleUp, 1.0);
605 
606 						    if(false)
607 						    {
608 							    // when really want to go to single pixel lines, move to center.
609 							    // Without this translation, all hor/ver hairlines will be centered exactly
610 							    // between two pixel lines (which looks best)
611 							    const double fTranslateToCenter(mnAntiAlialize * 0.5);
612 							    aTransform.translate(fTranslateToCenter, fTranslateToCenter, 0.0);
613 						    }
614 
615 						    aSnappedHairline.transform(aTransform);
616 
617 						    mpZBufferRasterConverter3D->rasterconvertB3DPolygon(aSnappedHairline, 0, mpBZPixelRaster->getHeight(), mnAntiAlialize);
618 					    }
619 					    else
620 					    {
621 						    mpZBufferRasterConverter3D->rasterconvertB3DPolygon(rHairline, 0, mpBZPixelRaster->getHeight(), mnAntiAlialize);
622 					    }
623 				    }
624 				    else
625 				    {
626 					    mpZBufferRasterConverter3D->rasterconvertB3DPolygon(rHairline, 0, mpBZPixelRaster->getHeight(), 1);
627 				    }
628                 }
629 			}
630 		}
631 
632 		void ZBufferProcessor3D::rasterconvertB3DPolyPolygon(const attribute::MaterialAttribute3D& rMaterial, const basegfx::B3DPolyPolygon& rFill) const
633 		{
634 			if(mpBZPixelRaster)
635 			{
636                 if(getTransparenceCounter())
637                 {
638                     // transparent output; record for later sorting and painting from
639                     // back to front
640                     if(!mpRasterPrimitive3Ds)
641                     {
642                         const_cast< ZBufferProcessor3D* >(this)->mpRasterPrimitive3Ds = new std::vector< RasterPrimitive3D >;
643                     }
644 
645                     mpRasterPrimitive3Ds->push_back(RasterPrimitive3D(
646                         getGeoTexSvx(),
647                         getTransparenceGeoTexSvx(),
648                         rMaterial,
649                         rFill,
650                         getModulate(),
651                         getFilter(),
652                         getSimpleTextureActive(),
653                         false));
654                 }
655                 else
656                 {
657                     mpZBufferRasterConverter3D->setCurrentMaterial(rMaterial);
658 				    mpZBufferRasterConverter3D->rasterconvertB3DPolyPolygon(rFill, &maInvEyeToView, 0, mpBZPixelRaster->getHeight());
659                 }
660 			}
661 		}
662 
663 		ZBufferProcessor3D::ZBufferProcessor3D(
664 			const geometry::ViewInformation3D& rViewInformation3D,
665 			const geometry::ViewInformation2D& rViewInformation2D,
666 			const attribute::SdrSceneAttribute& rSdrSceneAttribute,
667 			const attribute::SdrLightingAttribute& rSdrLightingAttribute,
668 			double fSizeX,
669 			double fSizeY,
670 			const basegfx::B2DRange& rVisiblePart,
671             sal_uInt16 nAntiAlialize)
672 		:	DefaultProcessor3D(rViewInformation3D, rSdrSceneAttribute, rSdrLightingAttribute),
673 			mpBZPixelRaster(0),
674 			maInvEyeToView(),
675 			mpZBufferRasterConverter3D(0),
676 			mnAntiAlialize(nAntiAlialize),
677             mpRasterPrimitive3Ds(0)
678 		{
679 			// generate ViewSizes
680 			const double fFullViewSizeX((rViewInformation2D.getObjectToViewTransformation() * basegfx::B2DVector(fSizeX, 0.0)).getLength());
681 			const double fFullViewSizeY((rViewInformation2D.getObjectToViewTransformation() * basegfx::B2DVector(0.0, fSizeY)).getLength());
682 			const double fViewSizeX(fFullViewSizeX * rVisiblePart.getWidth());
683 			const double fViewSizeY(fFullViewSizeY * rVisiblePart.getHeight());
684 
685             // generate RasterWidth and RasterHeight
686             const sal_uInt32 nRasterWidth((sal_uInt32)basegfx::fround(fViewSizeX) + 1);
687 			const sal_uInt32 nRasterHeight((sal_uInt32)basegfx::fround(fViewSizeY) + 1);
688 
689 			if(nRasterWidth && nRasterHeight)
690 			{
691 				// create view unit buffer
692 				mpBZPixelRaster = new basegfx::BZPixelRaster(
693 					mnAntiAlialize ? nRasterWidth * mnAntiAlialize : nRasterWidth,
694 					mnAntiAlialize ? nRasterHeight * mnAntiAlialize : nRasterHeight);
695 				OSL_ENSURE(mpBZPixelRaster, "ZBufferProcessor3D: Could not allocate basegfx::BZPixelRaster (!)");
696 
697 				// create DeviceToView for Z-Buffer renderer since Z is handled
698 				// different from standard 3D transformations (Z is mirrored). Also
699 				// the transformation includes the step from unit device coordinates
700 				// to discrete units ([-1.0 .. 1.0] -> [minDiscrete .. maxDiscrete]
701 
702 				basegfx::B3DHomMatrix aDeviceToView;
703 
704 				{
705 					// step one:
706 					//
707 					// bring from [-1.0 .. 1.0] in X,Y and Z to [0.0 .. 1.0]. Also
708 					// necessary to
709 					// - flip Y due to screen orientation
710 					// - flip Z due to Z-Buffer orientation from back to front
711 
712 					aDeviceToView.scale(0.5, -0.5, -0.5);
713 					aDeviceToView.translate(0.5, 0.5, 0.5);
714 				}
715 
716 				{
717 					// step two:
718 					//
719 					// bring from [0.0 .. 1.0] in X,Y and Z to view cordinates
720                     //
721 					// #i102611#
722                     // also: scale Z to [1.5 .. 65534.5]. Normally, a range of [0.0 .. 65535.0]
723                     // could be used, but a 'unused' value is needed, so '0' is used what reduces
724                     // the range to [1.0 .. 65535.0]. It has also shown that small numerical errors
725                     // (smaller as basegfx::fTools::mfSmallValue, which is 0.000000001) happen.
726                     // Instead of checking those by basegfx::fTools methods which would cost
727                     // runtime, just add another 0.5 tolerance to the start and end of the Z-Buffer
728                     // range, thus resulting in [1.5 .. 65534.5]
729 					const double fMaxZDepth(65533.0);
730 					aDeviceToView.translate(-rVisiblePart.getMinX(), -rVisiblePart.getMinY(), 0.0);
731 
732 					if(mnAntiAlialize)
733 						aDeviceToView.scale(fFullViewSizeX * mnAntiAlialize, fFullViewSizeY * mnAntiAlialize, fMaxZDepth);
734 					else
735 						aDeviceToView.scale(fFullViewSizeX, fFullViewSizeY, fMaxZDepth);
736 
737                     aDeviceToView.translate(0.0, 0.0, 1.5);
738 				}
739 
740 				// update local ViewInformation3D with own DeviceToView
741 				const geometry::ViewInformation3D aNewViewInformation3D(
742 					getViewInformation3D().getObjectTransformation(),
743 					getViewInformation3D().getOrientation(),
744 					getViewInformation3D().getProjection(),
745 					aDeviceToView,
746 					getViewInformation3D().getViewTime(),
747 					getViewInformation3D().getExtendedInformationSequence());
748 				updateViewInformation(aNewViewInformation3D);
749 
750 				// prepare inverse EyeToView transformation. This can be done in constructor
751 				// since changes in object transformations when processing TransformPrimitive3Ds
752 				// do not influence this prepared partial transformation
753 				maInvEyeToView = getViewInformation3D().getDeviceToView() * getViewInformation3D().getProjection();
754 				maInvEyeToView.invert();
755 
756 				// prepare maRasterRange
757 				maRasterRange.reset();
758 				maRasterRange.expand(basegfx::B2DPoint(0.0, 0.0));
759 				maRasterRange.expand(basegfx::B2DPoint(mpBZPixelRaster->getWidth(), mpBZPixelRaster->getHeight()));
760 
761 				// create the raster converter
762 				mpZBufferRasterConverter3D = new ZBufferRasterConverter3D(*mpBZPixelRaster, *this);
763 			}
764 		}
765 
766 		ZBufferProcessor3D::~ZBufferProcessor3D()
767 		{
768 			if(mpBZPixelRaster)
769 			{
770 				delete mpZBufferRasterConverter3D;
771 				delete mpBZPixelRaster;
772 			}
773 
774             if(mpRasterPrimitive3Ds)
775             {
776                 OSL_ASSERT("ZBufferProcessor3D: destructed, but there are unrendered transparent geometries. Use ZBufferProcessor3D::finish() to render these (!)");
777                 delete mpRasterPrimitive3Ds;
778             }
779 		}
780 
781         void ZBufferProcessor3D::finish()
782         {
783             if(mpRasterPrimitive3Ds)
784             {
785                 // there are transparent rasterprimitives
786                 const sal_uInt32 nSize(mpRasterPrimitive3Ds->size());
787 
788                 if(nSize > 1)
789                 {
790                     // sort them from back to front
791             		std::sort(mpRasterPrimitive3Ds->begin(), mpRasterPrimitive3Ds->end());
792                 }
793 
794                 for(sal_uInt32 a(0); a < nSize; a++)
795                 {
796                     // paint each one by setting the remembered data and calling
797                     // the render method
798                     const RasterPrimitive3D& rCandidate = (*mpRasterPrimitive3Ds)[a];
799 
800                     mpGeoTexSvx = rCandidate.getGeoTexSvx();
801                     mpTransparenceGeoTexSvx = rCandidate.getTransparenceGeoTexSvx();
802                     mbModulate = rCandidate.getModulate();
803                     mbFilter = rCandidate.getFilter();
804                     mbSimpleTextureActive = rCandidate.getSimpleTextureActive();
805 
806                     if(rCandidate.getIsLine())
807                     {
808                 		rasterconvertB3DPolygon(
809                             rCandidate.getMaterial(),
810                             rCandidate.getPolyPolygon().getB3DPolygon(0));
811                     }
812                     else
813                     {
814                 		rasterconvertB3DPolyPolygon(
815                             rCandidate.getMaterial(),
816                             rCandidate.getPolyPolygon());
817                     }
818                 }
819 
820                 // delete them to signal the destructor that all is done and
821                 // to allow asserting there
822                 delete mpRasterPrimitive3Ds;
823                 mpRasterPrimitive3Ds = 0;
824             }
825         }
826 
827         BitmapEx ZBufferProcessor3D::getBitmapEx() const
828 		{
829 			if(mpBZPixelRaster)
830 			{
831                 return BPixelRasterToBitmapEx(*mpBZPixelRaster, mnAntiAlialize);
832 			}
833 
834 			return BitmapEx();
835 		}
836 	} // end of namespace processor3d
837 } // end of namespace drawinglayer
838 
839 //////////////////////////////////////////////////////////////////////////////
840 // eof
841