Debian Codegraph @

third_party/rust/wpf-gpu-raster/src/aarasterizer.rs

raw
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4
5 #![allow(unused_parens)]
6
7 use std::cell::Cell;
8
9 use crate::aacoverage::c_nShift;
10 use crate::bezier::CMILBezier;
11 use crate::helpers::Int32x32To64;
12 use crate::matrix::CMILMatrix;
13 use crate::nullable_ref::Ref;
14 use crate::real::CFloatFPU;
15 //use crate::types::PathPointType::*;
16 use crate::types::*;
17 use typed_arena_nomut::Arena;
18
19 const S_OK: HRESULT = 0;
20
21 #[cfg(debug_assertions)]
22 macro_rules! EDGE_STORE_STACK_NUMBER {
23 () => {
24 10
25 };
26 }
27 #[cfg(debug_assertions)]
28 macro_rules! EDGE_STORE_ALLOCATION_NUMBER { () => { 11 }; }
29 #[cfg(debug_assertions)]
30 macro_rules! INACTIVE_LIST_NUMBER { () => { 12 }; }
31 #[cfg(debug_assertions)]
32 macro_rules! ENUMERATE_BUFFER_NUMBER { () => { 15 }; }
33
34 #[cfg(not(debug_assertions))]
35 macro_rules! EDGE_STORE_STACK_NUMBER { () => { (1600 / std::mem::size_of::<CEdge>()) }; }
36 #[cfg(not(debug_assertions))]
37 macro_rules! EDGE_STORE_ALLOCATION_NUMBER { () => { (4032 / std::mem::size_of::<CEdge>()) as u32 }; }
38 #[cfg(not(debug_assertions))]
39 macro_rules! INACTIVE_LIST_NUMBER { () => { EDGE_STORE_STACK_NUMBER!() }; }
40 #[cfg(not(debug_assertions))]
41 macro_rules! ENUMERATE_BUFFER_NUMBER { () => { 32 }; }
42
43 macro_rules! ASSERTACTIVELIST {
44 ($list: expr, $y: expr) => {
45 // make sure we use y even in non debug builds
46 _ = $y;
47 #[cfg(debug_assertions)]
48 AssertActiveList($list, $y);
49 };
50 }
51 pub struct CEdge<'a> {
52 pub Next: Cell<Ref<'a, CEdge<'a>>>, // Next active edge (don't check for NULL,
53 // look for tail sentinel instead)
54 pub X: Cell<INT>, // Current X location
55 pub Dx: INT, // X increment
56 pub Error: Cell<INT>, // Current DDA error
57 pub ErrorUp: INT, // Error increment
58 pub ErrorDown: INT, // Error decrement when the error rolls over
59 pub StartY: INT, // Y-row start
60 pub EndY: INT, // Y-row end
61 pub WindingDirection: INT, // -1 or 1
62 }
63
64 impl<'a> std::default::Default for CEdge<'a> {
65 fn default() -> Self {
66 Self {
67 Next: Cell::new(unsafe { Ref::null() }),
68 X: Default::default(),
69 Dx: Default::default(),
70 Error: Default::default(),
71 ErrorUp: Default::default(),
72 ErrorDown: Default::default(),
73 StartY: Default::default(),
74 EndY: Default::default(),
75 WindingDirection: Default::default(),
76 }
77 }
78 }
79
80 // We the inactive-array separate from the edge allocations so that
81 // we can more easily do in-place sorts on it:
82 #[derive(Clone)]
83 pub struct CInactiveEdge<'a> {
84 Edge: Ref<'a, CEdge<'a>>, // Associated edge
85 Yx: LONGLONG, // Sorting key, StartY and X packed into an lword
86 }
87
88 impl<'a> Default for CInactiveEdge<'a> {
89 fn default() -> Self {
90 Self {
91 Edge: unsafe { Ref::null() },
92 Yx: Default::default(),
93 }
94 }
95 }
96 macro_rules! ASSERTACTIVELISTORDER {
97 ($list: expr) => {
98 #[cfg(debug_assertions)]
99 AssertActiveListOrder($list)
100 };
101 }
102
103 /**************************************************************************\
104 *
105 * Function Description:
106 *
107 * Advance DDA and update active edge list
108 *
109 * Created:
110 *
111 * 06/20/2003 ashrafm
112 *
113 \**************************************************************************/
114 pub fn AdvanceDDAAndUpdateActiveEdgeList(nSubpixelYCurrent: INT, pEdgeActiveList: Ref<CEdge>) {
115 let mut outOfOrder = false;
116 let mut pEdgePrevious: Ref<CEdge> = pEdgeActiveList;
117 let mut pEdgeCurrent: Ref<CEdge> = pEdgeActiveList.Next.get();
118 let mut prevX = pEdgePrevious.X.get();
119
120 // Advance DDA and update edge list
121
122 loop {
123 if (pEdgeCurrent.EndY <= nSubpixelYCurrent) {
124 // If we've hit the sentinel, our work here is done:
125
126 if (pEdgeCurrent.EndY == INT::MIN) {
127 break; // ============>
128 }
129 // This edge is stale, remove it from the list:
130
131 pEdgeCurrent = pEdgeCurrent.Next.get();
132 pEdgePrevious.Next.set(pEdgeCurrent);
133 continue; // ============>
134 }
135
136 // Advance the DDA:
137
138 let mut x = pEdgeCurrent.X.get() + pEdgeCurrent.Dx;
139 let mut error = pEdgeCurrent.Error.get() + pEdgeCurrent.ErrorUp;
140 if (error >= 0) {
141 error -= pEdgeCurrent.ErrorDown;
142 x += 1;
143 }
144 pEdgeCurrent.X.set(x);
145 pEdgeCurrent.Error.set(error);
146
147 // Is this entry out-of-order with respect to the previous one?
148 outOfOrder |= (prevX > x);
149
150 // Advance:
151
152 pEdgePrevious = pEdgeCurrent;
153 pEdgeCurrent = pEdgeCurrent.Next.get();
154 prevX = x;
155 }
156
157 // It turns out that having any out-of-order edges at this point
158 // is extremely rare in practice, so only call the bubble-sort
159 // if it's truly needed.
160 //
161 // NOTE: If you're looking at this code trying to fix a bug where
162 // the edges are out of order when the filler is called, do
163 // NOT simply change the code to always do the bubble-sort!
164 // Instead, figure out what caused our 'outOfOrder' logic
165 // above to get messed up.
166
167 if (outOfOrder) {
168 SortActiveEdges(pEdgeActiveList);
169 }
170 ASSERTACTIVELISTORDER!(pEdgeActiveList);
171
172 }
173
174 //+----------------------------------------------------------------------------
175 //
176
177 //
178 // Description: Code for rasterizing the fill of a path.
179 //
180 // >>>> Note that some of this code is duplicated in hw\hwrasterizer.cpp,
181 // >>>> so changes to this file may need to propagate.
182 //
183 // pursue reduced code duplication
184 //
185
186 // This option may potentially increase performance for many
187 // paths that have edges adjacent at their top point and cover
188 // more than one span. The code has been tested, but performance
189 // has not been thoroughly investigated.
190 const SORT_EDGES_INCLUDING_SLOPE: bool = false;
191
192 /////////////////////////////////////////////////////////////////////////
193 // The x86 C compiler insists on making a divide and modulus operation
194 // into two DIVs, when it can in fact be done in one. So we use this
195 // macro.
196 //
197 // Note: QUOTIENT_REMAINDER implicitly takes unsigned arguments.
198 //
199 // QUOTIENT_REMAINDER_64_32 takes a 64-bit numerator and produces 32-bit
200 // results.
201
202 macro_rules! QUOTIENT_REMAINDER {
203 ($ulNumerator: ident, $ulDenominator: ident, $ulQuotient: ident, $ulRemainder: ident) => {
204 $ulQuotient = (($ulNumerator as ULONG) / ($ulDenominator as ULONG)) as _;
205 $ulRemainder = (($ulNumerator as ULONG) % ($ulDenominator as ULONG)) as _;
206 };
207 }
208
209 macro_rules! QUOTIENT_REMAINDER_64_32 {
210 ($ulNumerator: ident, $ulDenominator: ident, $ulQuotient: ident, $ulRemainder: ident) => {
211 $ulQuotient = (($ulNumerator as ULONGLONG) / (($ulDenominator as ULONG) as ULONGLONG)) as _;
212 $ulRemainder =
213 (($ulNumerator as ULONGLONG) % (($ulDenominator as ULONG) as ULONGLONG)) as _;
214 };
215 }
216
217 // SWAP macro:
218 macro_rules! SWAP {
219 ($temp: ident, $a: expr, $b: expr) => {
220 $temp = $a;
221 $a = $b;
222 $b = $temp;
223 };
224 }
225
226 struct CEdgeAllocation {
227 Next: *mut CEdgeAllocation, // Next allocation batch (may be NULL)
228 /*__field_range(<=, EDGE_STORE_ALLOCATION_NUMBER)*/ Count: UINT,
229 EdgeArray: [CEdge<'static>; EDGE_STORE_STACK_NUMBER!()],
230 }
231
232 impl Default for CEdgeAllocation {
233 fn default() -> Self {
234 Self { Next: NULL(), Count: Default::default(), EdgeArray: [(); EDGE_STORE_STACK_NUMBER!()].map(|_| Default::default()) }
235 }
236 }
237 /*
238 pub struct CEdgeStore {
239 /* __field_range(<=, UINT_MAX - 2) */ TotalCount: UINT, // Total edge count in store
240 /* __field_range(<=, CurrentBuffer->Count) */
241 CurrentRemaining: UINT, // How much room remains in current buffer
242 CurrentBuffer: *mut CEdgeAllocation, // Current buffer
243 CurrentEdge: *mut CEdge<'static>, // Current edge in current buffer
244 Enumerator: *mut CEdgeAllocation, // For enumerating all the edges
245 EdgeHead: CEdgeAllocation, // Our built-in allocation
246 }
247
248 impl Default for CEdgeStore {
249 fn default() -> Self {
250 Self { TotalCount: Default::default(), CurrentRemaining: Default::default(), CurrentBuffer: NULL(), CurrentEdge: NULL(), Enumerator: NULL(), EdgeHead: Default::default() }
251 }
252 }
253
254 impl CEdgeStore {
255 pub fn init(&mut self) {
256 self.TotalCount = 0;
257 self.CurrentBuffer = NULL();
258 self.CurrentEdge = NULL();
259 self.Enumerator = NULL();
260 self.CurrentRemaining = EDGE_STORE_STACK_NUMBER!() as u32;
261
262 self.EdgeHead = CEdgeAllocation {
263 Count: EDGE_STORE_STACK_NUMBER!() as u32,
264 // hack to work around limited Default implementation for arrays
265 EdgeArray: [(); EDGE_STORE_STACK_NUMBER!()].map(|_| Default::default()),
266 Next: NULL(),
267 };
268 self.CurrentBuffer = &mut self.EdgeHead;
269 self.CurrentEdge = &mut self.EdgeHead.EdgeArray[0];
270 }
271 }
272
273 impl Drop for CEdgeStore {
274 fn drop(&mut self) {
275 // Free our allocation list, skipping the head, which is not
276 // dynamically allocated:
277
278 let mut allocation: *mut CEdgeAllocation = self.EdgeHead.Next;
279 while (allocation != NULL()) {
280 let next = unsafe { (*allocation).Next };
281 drop(unsafe { Box::from_raw(allocation) });
282 allocation = next;
283 }
284 }
285 }
286
287 impl CEdgeStore {
288 pub fn StartEnumeration(&mut self) -> UINT {
289 unsafe {
290 self.Enumerator = &mut self.EdgeHead;
291
292 // Update the count and make sure nothing more gets added (in
293 // part because this Count would have to be re-computed):
294
295 (*self.CurrentBuffer).Count -= self.CurrentRemaining;
296
297 // This will never overflow because NextAddBuffer always ensures that TotalCount has
298 // space remaining to describe the capacity of all new buffers added to the edge list.
299 self.TotalCount += (*self.CurrentBuffer).Count;
300
301 // Prevent this from being called again, because bad things would
302 // happen:
303
304 self.CurrentBuffer = NULL();
305
306 return self.TotalCount;
307 }
308 }
309
310 fn Enumerate(
311 &mut self,
312 /*__deref_out_ecount(*ppEndEdge - *ppStartEdge)*/ ppStartEdge: &mut *mut CEdge,
313 /* __deref_out_ecount(0) */ ppEndEdge: &mut *mut CEdge,
314 ) -> bool {
315 /*
316 unsafe {
317 let enumerator: *mut CEdgeAllocation = self.Enumerator;
318
319 // Might return startEdge == endEdge:
320
321 *ppStartEdge = &mut (*enumerator).EdgeArray[0];
322 *ppEndEdge = (*ppStartEdge).offset((*enumerator).Count as isize);
323
324 self.Enumerator = (*enumerator).Next;
325 return (self.Enumerator != NULL());
326 }*/
327 return true;
328 }
329
330 fn StartAddBuffer(
331 &self,
332 /*__deref_out_ecount(*puRemaining)*/ ppCurrentEdge: &mut *mut CEdge,
333 /* __deref_out_range(==, (this->CurrentRemaining)) */ puRemaining: &mut UINT,
334 ) {
335 panic!()
336 // *ppCurrentEdge = self.CurrentEdge;
337 // *puRemaining = self.CurrentRemaining;
338 }
339
340 fn EndAddBuffer(
341 &mut self,
342 /*__in_ecount(remaining) */ pCurrentEdge: *mut CEdge,
343 /* __range(0, (this->CurrentBuffer->Count)) */ remaining: UINT,
344 ) {
345 panic!();
346 //self.CurrentEdge = pCurrentEdge;
347 //self.CurrentRemaining = remaining;
348 }
349
350 // Disable instrumentation checks within all methods of this class
351 //SET_MILINSTRUMENTATION_FLAGS(MILINSTRUMENTATIONFLAGS_DONOTHING);
352 }
353
354 /**************************************************************************\
355 *
356 * Function Description:
357 *
358 * The edge initializer is out of room in its current 'store' buffer;
359 * get it a new one.
360 *
361 * Created:
362 *
363 * 03/25/2000 andrewgo
364 *
365 \**************************************************************************/
366
367 impl CEdgeStore {
368 fn NextAddBuffer(
369 &mut self,
370 /*__deref_out_ecount(*puRemaining)*/ ppCurrentEdge: &mut *mut CEdge,
371 puRemaining: &mut UINT,
372 ) -> HRESULT {
373 panic!()
374 /*
375 unsafe {
376 let hr = S_OK;
377
378 let mut cNewTotalCount: u32 = 0;
379
380 // The caller has completely filled up this chunk:
381
382 assert!(*puRemaining == 0);
383
384 // Check to make sure that "TotalCount" will be able to represent the current capacity
385 cNewTotalCount = self.TotalCount + (*self.CurrentBuffer).Count;
386
387 if (cNewTotalCount < self.TotalCount) {
388 return WINCODEC_ERR_VALUEOVERFLOW;
389 }
390
391 // And that it can represent the new capacity as well, with at least 2 to spare.
392 // This "magic" 2 comes from the fact that the usage pattern of this class has callers
393 // needing to allocate space for TotalCount + 2 edges.
394 if (cNewTotalCount + ((EDGE_STORE_ALLOCATION_NUMBER!() + 2) as UINT) < cNewTotalCount) {
395 return WINCODEC_ERR_VALUEOVERFLOW;
396 }
397
398 // We have to grow our data structure by adding a new buffer
399 // and adding it to the list:
400
401 let newBuffer: *mut CEdgeAllocation = Box::into_raw(Box::<CEdgeAllocation>::new(Default::default()));/*static_cast<CEdgeAllocation*>
402 (GpMalloc(Mt(MAARasterizerEdge),
403 sizeof(CEdgeAllocation) +
404 sizeof(CEdge) * (EDGE_STORE_ALLOCATION_NUMBER
405 - EDGE_STORE_STACK_NUMBER)));*/
406 IFCOOM!(newBuffer);
407
408 (*newBuffer).Next = NULL();
409 (*newBuffer).Count = EDGE_STORE_STACK_NUMBER!() as u32;//EDGE_STORE_ALLOCATION_NUMBER!() as u32;
410
411 self.TotalCount = cNewTotalCount;
412
413 (*self.CurrentBuffer).Next = newBuffer;
414 self.CurrentBuffer = newBuffer;
415
416 self.CurrentEdge = &mut (*newBuffer).EdgeArray[0];
417 *ppCurrentEdge = panic!();//self.CurrentEdge;
418 self.CurrentRemaining = EDGE_STORE_STACK_NUMBER!() as u32;//EDGE_STORE_ALLOCATION_NUMBER!();
419 *puRemaining = EDGE_STORE_STACK_NUMBER!() as u32; //EDGE_STORE_ALLOCATION_NUMBER!();
420
421 return hr;
422 }*/
423 }
424 }
425 */
426 /**************************************************************************\
427 *
428 * Function Description:
429 *
430 * Some debug code for verifying the state of the active edge list.
431 *
432 * Created:
433 *
434 * 03/25/2000 andrewgo
435 *
436 \**************************************************************************/
437
438 pub fn AssertActiveList(mut list: Ref<CEdge>, yCurrent: INT) -> bool {
439
440 let mut b = true;
441 let mut activeCount = 0;
442
443 assert!((*list).X.get() == INT::MIN);
444 b &= ((*list).X.get() == INT::MIN);
445
446 // Skip the head sentinel:
447
448 list = (*list).Next.get();
449
450 while ((*list).X.get() != INT::MAX) {
451 assert!((*list).X.get() != INT::MIN);
452 b &= ((*list).X.get() != INT::MIN);
453
454 assert!((*list).X <= (*(*list).Next.get()).X);
455 b &= ((*list).X <= (*(*list).Next.get()).X);
456
457 assert!(((*list).StartY <= yCurrent) && (yCurrent < (*list).EndY));
458 b &= (((*list).StartY <= yCurrent) && (yCurrent < (*list).EndY));
459
460 activeCount += 1;
461 list = (*list).Next.get();
462 }
463
464 assert!((*list).X.get() == INT::MAX);
465 b &= ((*list).X.get() == INT::MAX);
466
467 // There should always be a multiple of 2 edges in the active list.
468 //
469 // NOTE: If you hit this assert, do NOT simply comment it out!
470 // It usually means that all the edges didn't get initialized
471 // properly. For every scan-line, there has to be a left edge
472 // and a right edge (or a multiple thereof). So if you give
473 // even a single bad edge to the edge initializer (or you miss
474 // one), you'll probably hit this assert.
475
476 assert!((activeCount & 1) == 0);
477 b &= ((activeCount & 1) == 0);
478
479 return (b);
480
481 }
482
483 /**************************************************************************\
484 *
485 * Function Description:
486 *
487 * Some debug code for verifying the state of the active edge list.
488 *
489 * Created:
490 *
491 * 03/25/2000 andrewgo
492 *
493 \**************************************************************************/
494
495 fn AssertActiveListOrder(mut list: Ref<CEdge>) {
496
497 assert!((*list).X.get() == INT::MIN);
498
499 // Skip the head sentinel:
500
501 list = (*list).Next.get();
502
503 while ((*list).X.get() != INT::MAX) {
504 assert!((*list).X.get() != INT::MIN);
505 assert!((*list).X <= (*(*list).Next.get()).X);
506
507 list = (*list).Next.get();
508 }
509
510 assert!((*list).X.get() == INT::MAX);
511 }
512
513 /**************************************************************************\
514 *
515 * Function Description:
516 *
517 * Clip the edge vertically.
518 *
519 * We've pulled this routine out-of-line from InitializeEdges mainly
520 * because it needs to call inline Asm, and when there is in-line
521 * Asm in a routine the compiler generally does a much less efficient
522 * job optimizing the whole routine. InitializeEdges is rather
523 * performance critical, so we avoid polluting the whole routine
524 * by having this functionality out-of-line.
525 *
526 * Created:
527 *
528 * 03/25/2000 andrewgo
529 *
530 \**************************************************************************/
531 fn ClipEdge(edgeBuffer: &mut CEdge, yClipTopInteger: INT, dMOriginal: INT) {
532 let mut xDelta: INT;
533 let mut error: INT;
534
535 // Cases where bigNumerator will exceed 32-bits in precision
536 // will be rare, but could happen, and we can't fall over
537 // in those cases.
538
539 let dN: INT = edgeBuffer.ErrorDown;
540 let mut bigNumerator: LONGLONG = Int32x32To64(dMOriginal, yClipTopInteger - edgeBuffer.StartY)
541 + (edgeBuffer.Error.get() + dN) as LONGLONG;
542 if (bigNumerator >= 0) {
543 QUOTIENT_REMAINDER_64_32!(bigNumerator, dN, xDelta, error);
544 } else {
545 bigNumerator = -bigNumerator;
546 QUOTIENT_REMAINDER_64_32!(bigNumerator, dN, xDelta, error);
547
548 xDelta = -xDelta;
549 if (error != 0) {
550 xDelta -= 1;
551 error = dN - error;
552 }
553 }
554
555 // Update the edge data structure with the results:
556
557 edgeBuffer.StartY = yClipTopInteger;
558 edgeBuffer.X.set(edgeBuffer.X.get() + xDelta);
559 edgeBuffer.Error.set(error - dN); // Renormalize error
560 }
561
562 pub fn CheckValidRange28_4(x: f32, y: f32) -> bool {
563 //
564 // We want coordinates in the 28.4 range in the end. The matrix we get
565 // as input includes the scale by 16 to get to 28.4, so we want to
566 // ensure that we are in integer range. Assuming a sign bit and
567 // five bits for the rasterizer working range, we want coordinates in the
568 // -2^26 to 2^26.
569 //
570 // Note that the 5-bit requirement comes from the
571 // implementation of InitializeEdges.
572 // (See line with "error -= dN * (16 - (xStart & 15))")
573 //
574 // Anti-aliasing uses another c_nShift bits, so we get a
575 // desired range of -2^(26-c_nShift) to 2^(26-c_nShift)
576 //
577 let rPixelCoordinateMax = (1 << (26 - c_nShift)) as f32;
578 let rPixelCoordinateMin = -rPixelCoordinateMax;
579 return x <= rPixelCoordinateMax && x >= rPixelCoordinateMin
580 && y <= rPixelCoordinateMax && y >= rPixelCoordinateMin;
581 }
582
583 //+-----------------------------------------------------------------------------
584 //
585 // Function: TransformRasterizerPointsTo28_4
586 //
587 // Synopsis:
588 // Transform rasterizer points to 28.4. If overflow occurs, return that
589 // information.
590 //
591 //------------------------------------------------------------------------------
592 fn TransformRasterizerPointsTo28_4(
593 pmat: &CMILMatrix,
594 // Transform to take us to 28.4
595 mut pPtsSource: &[MilPoint2F],
596 // Source points
597 mut cPoints: UINT,
598 // Count of points
599 mut pPtsDest: &mut [POINT], // Destination points
600 ) -> HRESULT {
601 let hr = S_OK;
602
603 debug_assert!(cPoints > 0);
604
605 while {
606 //
607 // Transform coordinates
608 //
609
610 let rPixelX =
611 (pmat.GetM11() * pPtsSource[0].X) + (pmat.GetM21() * pPtsSource[0].Y) + pmat.GetDx();
612 let rPixelY =
613 (pmat.GetM12() * pPtsSource[0].X) + (pmat.GetM22() * pPtsSource[0].Y) + pmat.GetDy();
614
615 //
616 // Check for NaNs or overflow
617 //
618
619 if !CheckValidRange28_4(rPixelX, rPixelY) {
620 return WGXERR_BADNUMBER;
621 }
622
623 //
624 // Assign coordinates
625 //
626
627 pPtsDest[0].x = CFloatFPU::Round(rPixelX);
628 pPtsDest[0].y = CFloatFPU::Round(rPixelY);
629
630 pPtsDest = &mut pPtsDest[1..];
631 pPtsSource = &pPtsSource[1..];
632 cPoints -= 1;
633 cPoints != 0
634 } {}
635
636 return hr;
637 }
638
639 pub fn AppendScaleToMatrix(pmat: &mut CMILMatrix, scaleX: REAL, scaleY: REAL) {
640 pmat.SetM11(pmat.GetM11() * scaleX);
641 pmat.SetM21(pmat.GetM21() * scaleX);
642 pmat.SetM12(pmat.GetM12() * scaleY);
643 pmat.SetM22(pmat.GetM22() * scaleY);
644 pmat.SetDx(pmat.GetDx() * scaleX);
645 pmat.SetDy(pmat.GetDy() * scaleY);
646 }
647
648 /**************************************************************************\
649 *
650 * Function Description:
651 *
652 * Add edges to the edge list.
653 *
654 * Created:
655 *
656 * 03/25/2000 andrewgo
657 *
658 \**************************************************************************/
659
660 pub struct CInitializeEdgesContext<'a> {
661 pub MaxY: INT, // Maximum 'y' found, should be INT_MIN on
662 // first call to 'InitializeEdges'
663 pub ClipRect: Option<&'a RECT>, // Bounding clip rectangle in 28.4 format
664 pub Store: &'a Arena<CEdge<'a>>, // Where to stick the edges
665 pub AntiAliasMode: MilAntiAliasMode,
666 }
667
668 impl<'a> CInitializeEdgesContext<'a> {
669 pub fn new(store: &'a Arena<CEdge<'a>>) -> Self {
670 CInitializeEdgesContext { MaxY: Default::default(), ClipRect: Default::default(), Store: store, AntiAliasMode: MilAntiAliasMode::None }
671 }
672 }
673
674 fn InitializeEdges(
675 pEdgeContext: &mut CInitializeEdgesContext,
676 /*__inout_ecount(vertexCount)*/
677 mut pointArray: &mut [POINT], // Points to a 28.4 array of size 'vertexCount'
678 // Note that we may modify the contents!
679 /*__in_range(>=, 2)*/ vertexCount: UINT,
680 ) -> HRESULT {
681 // Disable instrumentation checks for this function
682 //SET_MILINSTRUMENTATION_FLAGS(MILINSTRUMENTATIONFLAGS_DONOTHING);
683
684 let hr = S_OK;
685
686 let mut xStart;
687 let mut yStart;
688 let mut yStartInteger;
689 let mut yEndInteger;
690 let mut dMOriginal;
691 let mut dM: i32;
692 let mut dN: i32;
693 let mut dX: i32;
694 let mut errorUp: i32;
695 let mut quotient: i32;
696 let mut remainder: i32;
697 let mut error: i32;
698 let mut windingDirection;
699 //let mut edgeBuffer: *mut CEdge = NULL();
700 let bufferCount: UINT = 0;
701 let mut yClipTopInteger;
702 let mut yClipTop;
703 let mut yClipBottom;
704 let mut xClipLeft;
705 let mut xClipRight;
706
707 let mut yMax = pEdgeContext.MaxY;
708 let _store = &mut pEdgeContext.Store;
709 let clipRect = pEdgeContext.ClipRect;
710
711 let mut edgeCount = vertexCount - 1;
712 assert!(edgeCount >= 1);
713
714 if let Some(clipRect) = clipRect {
715 yClipTopInteger = clipRect.top >> 4;
716 yClipTop = clipRect.top;
717 yClipBottom = clipRect.bottom;
718 xClipLeft = clipRect.left;
719 xClipRight = clipRect.right;
720
721 assert!(yClipBottom > 0);
722 assert!(yClipTop <= yClipBottom);
723 } else {
724 yClipBottom = 0;
725 yClipTopInteger = INT::MIN >> c_nShift;
726
727 // These 3 values are only used when clipRect is non-NULL
728 yClipTop = 0;
729 xClipLeft = 0;
730 xClipRight = 0;
731 }
732
733 if (pEdgeContext.AntiAliasMode != MilAntiAliasMode::None) {
734 // If antialiasing, apply the supersampling scaling here before we
735 // calculate the DDAs. We do this here and not in the Matrix
736 // transform we give to FixedPointPathEnumerate mainly so that the
737 // Bezier flattener can continue to operate in its optimal 28.4
738 // format.
739 //
740 // PS#856364-2003/07/01-JasonHa Remove pixel center fixup
741 //
742 // We also apply a half-pixel offset here so that the antialiasing
743 // code can assume that the pixel centers are at half-pixel
744 // coordinates, not on the integer coordinates.
745
746 let mut point = &mut *pointArray;
747 let mut i = vertexCount;
748
749 while {
750 point[0].x = (point[0].x + 8) << c_nShift;
751 point[0].y = (point[0].y + 8) << c_nShift;
752 point = &mut point[1..];
753 i -= 1;
754 i != 0
755 } {}
756
757 yClipTopInteger <<= c_nShift;
758 yClipTop <<= c_nShift;
759 yClipBottom <<= c_nShift;
760 xClipLeft <<= c_nShift;
761 xClipRight <<= c_nShift;
762 }
763
764 // Make 'yClipBottom' inclusive by subtracting off one pixel
765 // (keeping in mind that we're in 28.4 device space):
766
767 yClipBottom -= 16;
768
769 // Warm up the store where we keep the edge data:
770
771 //store.StartAddBuffer(&mut edgeBuffer, &mut bufferCount);
772
773 'outer: loop { loop {
774 // Handle trivial rejection:
775
776 if (yClipBottom >= 0) {
777 // Throw out any edges that are above or below the clipping.
778 // This has to be a precise check, because we assume later
779 // on that every edge intersects in the vertical dimension
780 // with the clip rectangle. That asssumption is made in two
781 // places:
782 //
783 // 1. When we sort the edges, we assume either zero edges,
784 // or two or more.
785 // 2. When we start the DDAs, we assume either zero edges,
786 // or that there's at least one scan of DDAs to output.
787 //
788 // Plus, of course, it's less efficient if we let things
789 // through.
790 //
791 // Note that 'yClipBottom' is inclusive:
792
793 let clipHigh = ((pointArray[0]).y <= yClipTop) && ((pointArray[1]).y <= yClipTop);
794
795 let clipLow = ((pointArray[0]).y > yClipBottom) && ((pointArray[1]).y > yClipBottom);
796
797 #[cfg(debug_assertions)]
798 {
799 let (mut yRectTop, mut yRectBottom, y0, y1, yTop, yBottom);
800
801 // Getting the trivial rejection code right is tricky.
802 // So on checked builds let's verify that we're doing it
803 // correctly, using a different approach:
804
805 let mut clipped = false;
806 if let Some(clipRect) = clipRect {
807 yRectTop = clipRect.top >> 4;
808 yRectBottom = clipRect.bottom >> 4;
809 if (pEdgeContext.AntiAliasMode != MilAntiAliasMode::None) {
810 yRectTop <<= c_nShift;
811 yRectBottom <<= c_nShift;
812 }
813 y0 = ((pointArray[0]).y + 15) >> 4;
814 y1 = ((pointArray[1]).y + 15) >> 4;
815 yTop = y0.min(y1);
816 yBottom = y0.max(y1);
817
818 clipped = ((yTop >= yRectBottom) || (yBottom <= yRectTop));
819 }
820
821 assert!(clipped == (clipHigh || clipLow));
822 }
823
824 if (clipHigh || clipLow) {
825 break; // ======================>
826 }
827
828 if (edgeCount > 1) {
829 // Here we'll collapse two edges down to one if both are
830 // to the left or to the right of the clipping rectangle.
831
832 if (((pointArray[0]).x < xClipLeft)
833 && ((pointArray[1]).x < xClipLeft)
834 && ((pointArray[2]).x < xClipLeft))
835 {
836 // Note this is one reason why 'pointArray' can't be 'const':
837
838 pointArray[1] = pointArray[0];
839
840 break; // ======================>
841 }
842
843 if (((pointArray[0]).x > xClipRight)
844 && ((pointArray[1]).x > xClipRight)
845 && ((pointArray[2]).x > xClipRight))
846 {
847 // Note this is one reason why 'pointArray' can't be 'const':
848
849 pointArray[1] = pointArray[0];
850
851 break; // ======================>
852 }
853 }
854 }
855
856 dM = (pointArray[1]).x - (pointArray[0]).x;
857 dN = (pointArray[1]).y - (pointArray[0]).y;
858
859 if (dN >= 0) {
860 // The vector points downward:
861
862 xStart = (pointArray[0]).x;
863 yStart = (pointArray[0]).y;
864
865 yStartInteger = (yStart + 15) >> 4;
866 yEndInteger = ((pointArray[1]).y + 15) >> 4;
867
868 windingDirection = 1;
869 } else {
870 // The vector points upward, so we have to essentially
871 // 'swap' the end points:
872
873 dN = -dN;
874 dM = -dM;
875
876 xStart = (pointArray[1]).x;
877 yStart = (pointArray[1]).y;
878
879 yStartInteger = (yStart + 15) >> 4;
880 yEndInteger = ((pointArray[0]).y + 15) >> 4;
881
882 windingDirection = -1;
883 }
884
885 // The edgeBuffer must span an integer y-value in order to be
886 // added to the edgeBuffer list. This serves to get rid of
887 // horizontal edges, which cause trouble for our divides.
888
889 if (yEndInteger > yStartInteger) {
890 yMax = yMax.max(yEndInteger);
891
892 dMOriginal = dM;
893 if (dM < 0) {
894 dM = -dM;
895 if (dM < dN)
896 // Can't be '<='
897 {
898 dX = -1;
899 errorUp = dN - dM;
900 } else {
901 QUOTIENT_REMAINDER!(dM, dN, quotient, remainder);
902
903 dX = -quotient;
904 errorUp = remainder;
905 if (remainder > 0) {
906 dX = -quotient - 1;
907 errorUp = dN - remainder;
908 }
909 }
910 } else {
911 if (dM < dN) {
912 dX = 0;
913 errorUp = dM;
914 } else {
915 QUOTIENT_REMAINDER!(dM, dN, quotient, remainder);
916
917 dX = quotient;
918 errorUp = remainder;
919 }
920 }
921
922 error = -1; // Error is initially zero (add dN - 1 for
923 // the ceiling, but subtract off dN so that
924 // we can check the sign instead of comparing
925 // to dN)
926
927 if ((yStart & 15) != 0) {
928 // Advance to the next integer y coordinate
929
930 let mut i = 16 - (yStart & 15);
931 while i != 0 {
932 xStart += dX;
933 error += errorUp;
934 if (error >= 0)
935 {
936 error -= dN;
937 xStart += 1;
938 }
939 i -= 1;
940 }
941 }
942
943 if ((xStart & 15) != 0) {
944 error -= dN * (16 - (xStart & 15));
945 xStart += 15; // We'll want the ceiling in just a bit...
946 }
947
948 xStart >>= 4;
949 error >>= 4;
950
951 if (bufferCount == 0) {
952 //IFC!(store.NextAddBuffer(&mut edgeBuffer, &mut bufferCount));
953 }
954
955 let mut edge = CEdge {
956 Next: Cell::new(unsafe { Ref::null() } ),
957 X: Cell::new(xStart),
958 Dx: dX,
959 Error: Cell::new(error),
960 ErrorUp: errorUp,
961 ErrorDown: dN,
962 WindingDirection: windingDirection,
963 StartY: yStartInteger,
964 EndY: yEndInteger,// Exclusive of end
965 };
966
967 assert!(error < 0);
968
969 // Here we handle the case where the edge starts above the
970 // clipping rectangle, and we need to jump down in the 'y'
971 // direction to the first unclipped scan-line.
972 //
973 // Consequently, we advance the DDA here:
974
975 if (yClipTopInteger > yStartInteger) {
976 assert!(edge.EndY > yClipTopInteger);
977
978 ClipEdge(&mut edge, yClipTopInteger, dMOriginal);
979 }
980
981 // Advance to handle the next edge:
982
983 //edgeBuffer = unsafe { edgeBuffer.offset(1) };
984 pEdgeContext.Store.alloc(edge);
985 //bufferCount -= 1;
986 }
987 break;
988 }
989 pointArray = &mut pointArray[1..];
990 edgeCount -= 1;
991 if edgeCount == 0 {
992 break 'outer;
993 }
994 }
995
996 // We're done with this batch. Let the store know how many edges
997 // we ended up with:
998
999 //store.EndAddBuffer(edgeBuffer, bufferCount);
1000
1001 pEdgeContext.MaxY = yMax;
1002
1003 return hr;
1004 }
1005
1006 /**************************************************************************\
1007 *
1008 * Function Description:
1009 *
1010 * Does complete parameter checking on the 'types' array of a path.
1011 *
1012 * Created:
1013 *
1014 * 03/25/2000 andrewgo
1015 *
1016 \**************************************************************************/
1017 fn ValidatePathTypes(typesArray: &[BYTE], mut count: INT) -> bool {
1018 let mut types = typesArray;
1019
1020 if (count == 0) {
1021 return (true);
1022 }
1023
1024 loop {
1025 // The first point in every subpath has to be an unadorned
1026 // 'start' point:
1027
1028 if ((types[0] & PathPointTypePathTypeMask) != PathPointTypeStart) {
1029 TraceTag!((tagMILWarning, "Bad subpath start"));
1030 return (false);
1031 }
1032
1033 // Advance to the first point after the 'start' point:
1034 count -= 1;
1035 if (count == 0) {
1036 TraceTag!((tagMILWarning, "Path ended after start-path"));
1037 return (false);
1038 }
1039
1040 if ((types[1] & PathPointTypePathTypeMask) == PathPointTypeStart) {
1041 TraceTag!((tagMILWarning, "Can't have a start followed by a start!"));
1042 return (false);
1043 }
1044
1045 // Process runs of lines and Bezier curves:
1046
1047 loop {
1048 match (types[1] & PathPointTypePathTypeMask) {
1049 PathPointTypeLine => {
1050 types = &types[1..];
1051 count -= 1;
1052 if (count == 0) {
1053 return (true);
1054 }
1055 }
1056
1057 PathPointTypeBezier => {
1058 if (count < 3) {
1059 TraceTag!((
1060 tagMILWarning,
1061 "Path ended before multiple of 3 Bezier points"
1062 ));
1063 return (false);
1064 }
1065
1066 if ((types[1] & PathPointTypePathTypeMask) != PathPointTypeBezier) {
1067 TraceTag!((tagMILWarning, "Bad subpath start"));
1068 return (false);
1069 }
1070
1071 types = &types[1..];
1072 count -= 3;
1073 if (count == 0) {
1074 return (true);
1075 }
1076 }
1077
1078 _ => {
1079 TraceTag!((tagMILWarning, "Illegal type"));
1080 return (false);
1081 }
1082 }
1083
1084 // A close-subpath marker or a start-subpath marker marks the
1085 // end of a subpath:
1086 if !(!((types[0] & PathPointTypeCloseSubpath) != 0)
1087 && ((types[1] & PathPointTypePathTypeMask) != PathPointTypeStart)) {
1088 types = &types[1..];
1089 break;
1090 }
1091 }
1092 }
1093 }
1094
1095 /**************************************************************************\
1096 *
1097 * Function Description:
1098 *
1099 * Some debug code for verifying the path.
1100 *
1101 * Created:
1102 *
1103 * 03/25/2000 andrewgo
1104 *
1105 \**************************************************************************/
1106 macro_rules! ASSERTPATH {
1107 ($types: expr, $points: expr) => {
1108 #[cfg(debug_assertions)]
1109 AssertPath($types, $points)
1110 };
1111 }
1112 fn AssertPath(rgTypes: &[BYTE], cPoints: UINT) {
1113 // Make sure that the 'types' array is well-formed, otherwise we
1114 // may fall over in the FixedPointPathEnumerate function.
1115 //
1116 // NOTE: If you hit this assert, DO NOT SIMPLY COMMENT THIS Assert OUT!
1117 //
1118 // Instead, fix the ValidatePathTypes code if it's letting through
1119 // valid paths, or (more likely) fix the code that's letting bogus
1120 // paths through. The FixedPointPathEnumerate routine has some
1121 // subtle assumptions that require the path to be perfectly valid!
1122 //
1123 // No internal code should be producing invalid paths, and all
1124 // paths created by the application must be parameter checked!
1125 assert!(ValidatePathTypes(rgTypes, cPoints as INT));
1126 }
1127
1128 //+----------------------------------------------------------------------------
1129 //
1130 // Member:
1131 // FixedPointPathEnumerate
1132 //
1133 // Synopsis:
1134 //
1135 // Enumerate the path.
1136 //
1137 // NOTE: The 'enumerateFunction' function is allowed to modify the
1138 // contents of our call-back buffer! (This is mainly done to allow
1139 // 'InitializeEdges' to be simpler for some clipping trivial
1140 // rejection cases.)
1141 //
1142 // NOTICE-2006/03/22-milesc This function was initially built to be a
1143 // general path enumeration function. However, we were only using it for
1144 // one specific purpose... for Initializing edges of a path to be filled.
1145 // In doing security work, I simplified this function to just do edge
1146 // initialization. The name is therefore now overly general. I have kept
1147 // the name to be a reminder that this function has been written to be
1148 // more general than would otherwise be evident.
1149 //
1150
1151 pub fn FixedPointPathEnumerate(
1152 rgpt: &[POINT],
1153 rgTypes: &[BYTE],
1154 cPoints: UINT,
1155 _matrix: &CMILMatrix,
1156 clipRect: Option<&RECT>, // In scaled 28.4 format
1157 enumerateContext: &mut CInitializeEdgesContext,
1158 ) -> HRESULT {
1159 let hr = S_OK;
1160 let mut bufferStart: [POINT; ENUMERATE_BUFFER_NUMBER!()] = [(); ENUMERATE_BUFFER_NUMBER!()].map(|_| Default::default());
1161 let mut bezierBuffer: [POINT; 4] = Default::default();
1162 let mut buffer: &mut [POINT];
1163 let mut bufferSize: usize;
1164 let mut startFigure: [POINT; 1] = Default::default();
1165 // The current point offset in rgpt
1166 let mut iPoint: usize;
1167 // The current type offset in rgTypes
1168 let mut iType: usize;
1169 let mut runSize: usize;
1170 let mut thisCount: usize;
1171 let mut isMore: bool = false;
1172 let mut xLast: INT;
1173 let mut yLast: INT;
1174
1175 ASSERTPATH!(rgTypes, cPoints);
1176
1177 // Every valid subpath has at least two vertices in it, hence the
1178 // check of 'cPoints - 1':
1179
1180 iPoint = 0;
1181 iType = 0;
1182
1183 assert!(cPoints > 1);
1184 while (iPoint < cPoints as usize - 1) {
1185 assert!((rgTypes[iType] & PathPointTypePathTypeMask) == PathPointTypeStart);
1186 assert!((rgTypes[iType + 1] & PathPointTypePathTypeMask) != PathPointTypeStart);
1187
1188 // Add the start point to the beginning of the batch, and
1189 // remember it for handling the close figure:
1190
1191 startFigure[0] = rgpt[iPoint];
1192
1193 bufferStart[0].x = startFigure[0].x;
1194 bufferStart[0].y = startFigure[0].y;
1195 let bufferStartPtr = bufferStart.as_ptr();
1196 buffer = &mut bufferStart[1..];
1197 bufferSize = ENUMERATE_BUFFER_NUMBER!() - 1;
1198
1199 // We need to enter our loop with 'iType' pointing one past
1200 // the start figure:
1201
1202 iPoint += 1;
1203 iType += 1;
1204
1205 while {
1206 // Try finding a run of lines:
1207
1208 if ((rgTypes[iType] & PathPointTypePathTypeMask) == PathPointTypeLine) {
1209 runSize = 1;
1210
1211 while ((iPoint + runSize < cPoints as usize)
1212 && ((rgTypes[iType + runSize] & PathPointTypePathTypeMask) == PathPointTypeLine))
1213 {
1214 runSize += 1;
1215 }
1216
1217 // Okay, we've found a run of lines. Break it up into our
1218 // buffer size:
1219
1220 loop {
1221 thisCount = bufferSize.min(runSize);
1222
1223 buffer[0 .. thisCount].copy_from_slice(&rgpt[iPoint .. iPoint + thisCount]);
1224
1225 __analysis_assume!(
1226 buffer + bufferSize == bufferStart + ENUMERATE_BUFFER_NUMBER
1227 );
1228 assert!(buffer.as_ptr().wrapping_offset(bufferSize as isize) == bufferStartPtr.wrapping_offset(ENUMERATE_BUFFER_NUMBER!()) );
1229
1230 iPoint += thisCount;
1231 iType += thisCount;
1232 buffer = &mut buffer[thisCount..];
1233 runSize -= thisCount;
1234 bufferSize -= thisCount;
1235
1236 if (bufferSize > 0) {
1237 break;
1238 }
1239
1240 xLast = bufferStart[ENUMERATE_BUFFER_NUMBER!() - 1].x;
1241 yLast = bufferStart[ENUMERATE_BUFFER_NUMBER!() - 1].y;
1242 IFR!(InitializeEdges(
1243 enumerateContext,
1244 &mut bufferStart,
1245 ENUMERATE_BUFFER_NUMBER!()
1246 ));
1247
1248 // Continue the last vertex as the first in the new batch:
1249
1250 bufferStart[0].x = xLast;
1251 bufferStart[0].y = yLast;
1252 buffer = &mut bufferStart[1..];
1253 bufferSize = ENUMERATE_BUFFER_NUMBER!() - 1;
1254 if !(runSize != 0) {
1255 break;
1256 }
1257 }
1258 } else {
1259 assert!(iPoint + 3 <= cPoints as usize);
1260 assert!((rgTypes[iType] & PathPointTypePathTypeMask) == PathPointTypeBezier);
1261
1262 bezierBuffer.copy_from_slice(&rgpt[(iPoint - 1) .. iPoint + 3]);
1263
1264 // Prepare for the next iteration:
1265
1266 iPoint += 3;
1267 iType += 1;
1268
1269 // Process the Bezier:
1270
1271 let mut bezier = CMILBezier::new(&bezierBuffer, clipRect);
1272 loop {
1273 thisCount = bezier.Flatten(buffer, &mut isMore) as usize;
1274
1275 __analysis_assume!(
1276 buffer + bufferSize == bufferStart + ENUMERATE_BUFFER_NUMBER!()
1277 );
1278 assert!(buffer.as_ptr().wrapping_offset(bufferSize as isize) == bufferStartPtr.wrapping_offset(ENUMERATE_BUFFER_NUMBER!()));
1279
1280 buffer = &mut buffer[thisCount..];
1281 bufferSize -= thisCount;
1282
1283 if (bufferSize > 0) {
1284 break;
1285 }
1286
1287 xLast = bufferStart[ENUMERATE_BUFFER_NUMBER!() - 1].x;
1288 yLast = bufferStart[ENUMERATE_BUFFER_NUMBER!() - 1].y;
1289 IFR!(InitializeEdges(
1290 enumerateContext,
1291 &mut bufferStart,
1292 ENUMERATE_BUFFER_NUMBER!()
1293 ));
1294
1295 // Continue the last vertex as the first in the new batch:
1296
1297 bufferStart[0].x = xLast;
1298 bufferStart[0].y = yLast;
1299 buffer = &mut bufferStart[1..];
1300 bufferSize = ENUMERATE_BUFFER_NUMBER!() - 1;
1301 if !isMore {
1302 break;
1303 }
1304 }
1305 }
1306
1307 ((iPoint < cPoints as usize)
1308 && ((rgTypes[iType] & PathPointTypePathTypeMask) != PathPointTypeStart))
1309 } {}
1310
1311 // Okay, the subpath is done. But we still have to handle the
1312 // 'close figure' (which is implicit for a fill):
1313 // Add the close-figure point:
1314
1315 buffer[0].x = startFigure[0].x;
1316 buffer[0].y = startFigure[0].y;
1317 bufferSize -= 1;
1318
1319 // We have to flush anything we might have in the batch, unless
1320 // there's only one vertex in there! (The latter case may happen
1321 // for the stroke case with no close figure if we just flushed a
1322 // batch.)
1323 // If we're flattening, we must call the one additional time to
1324 // correctly handle closing the subpath, even if there is only
1325 // one entry in the batch. The flattening callback handles the
1326 // one point case and closes the subpath properly without adding
1327 // extraneous points.
1328
1329 let verticesInBatch = ENUMERATE_BUFFER_NUMBER!() - bufferSize;
1330 if (verticesInBatch > 1) {
1331 IFR!(InitializeEdges(
1332 enumerateContext,
1333 &mut bufferStart,
1334 (verticesInBatch) as UINT
1335 ));
1336 }
1337 }
1338
1339 return hr;
1340 }
1341
1342 /**************************************************************************\
1343 *
1344 * Function Description:
1345 *
1346 * We want to sort in the inactive list; the primary key is 'y', and
1347 * the secondary key is 'x'. This routine creates a single LONGLONG
1348 * key that represents both.
1349 *
1350 * Created:
1351 *
1352 * 03/25/2000 andrewgo
1353 *
1354 \**************************************************************************/
1355
1356 fn YX(x: INT, y: INT, p: &mut LONGLONG) {
1357 // Bias 'x' by INT_MAX so that it's effectively unsigned:
1358 /*
1359 reinterpret_cast<LARGE_INTEGER*>(p)->HighPart = y;
1360 reinterpret_cast<LARGE_INTEGER*>(p)->LowPart = x + INT_MAX;
1361 */
1362 *p = (((y as u64) << 32) | (((x as i64 + i32::MAX as i64) as u64) & 0xffffffff)) as i64;
1363 }
1364
1365 /**************************************************************************\
1366 *
1367 * Function Description:
1368 *
1369 * Recursive function to quick-sort our inactive edge list. Note that
1370 * for performance, the results are not completely sorted; an insertion
1371 * sort has to be run after the quicksort in order to do a lighter-weight
1372 * sort of the subtables.
1373 *
1374 * Created:
1375 *
1376 * 03/25/2000 andrewgo
1377 *
1378 \**************************************************************************/
1379
1380 const QUICKSORT_THRESHOLD: isize = 8;
1381
1382 fn QuickSortEdges(inactive: &mut [CInactiveEdge],
1383 /*__inout_xcount(f - l + 1 elements)*/ f: usize,
1384 /*__inout_xcount(array starts at f)*/ l: usize,
1385 ) {
1386 let mut e: Ref<CEdge>;
1387 let mut y: LONGLONG;
1388 let mut first: LONGLONG;
1389 let mut second: LONGLONG;
1390 let mut last: LONGLONG;
1391
1392 // Find the median of the first, middle, and last elements:
1393
1394 let m = f + ((l - f) >> 1);
1395
1396 SWAP!(y, inactive[f + 1].Yx, inactive[m].Yx);
1397 SWAP!(e, inactive[f + 1].Edge, inactive[m].Edge);
1398
1399 if {second = inactive[f + 1].Yx; second > {last = inactive[l].Yx; last}} {
1400 inactive[f + 1].Yx = last;
1401 inactive[l].Yx = second;
1402
1403 SWAP!(e, inactive[f + 1].Edge, inactive[l].Edge);
1404 }
1405 if {first = inactive[f].Yx; first} > {last = inactive[l].Yx; last} {
1406 inactive[f].Yx = last;
1407 inactive[l].Yx = first;
1408
1409 SWAP!(e, inactive[f].Edge, inactive[l].Edge);
1410 }
1411 if {second = inactive[f + 1].Yx; second} > {first = inactive[f].Yx; first} {
1412 inactive[f + 1].Yx = first;
1413 inactive[f].Yx = second;
1414
1415 SWAP!(e, inactive[f + 1].Edge, inactive[f].Edge);
1416 }
1417
1418 // f->Yx is now the desired median, and (f + 1)->Yx <= f->Yx <= l->Yx
1419
1420 debug_assert!((inactive[f + 1].Yx <= inactive[f].Yx) && (inactive[f].Yx <= inactive[l].Yx));
1421
1422 let median = inactive[f].Yx;
1423
1424 let mut i = f + 2;
1425 while (inactive[i].Yx < median) {
1426 i += 1;
1427 }
1428
1429 let mut j = l - 1;
1430 while (inactive[j].Yx > median) {
1431 j -= 1;
1432 }
1433
1434 while (i < j) {
1435 SWAP!(y, inactive[i].Yx, inactive[j].Yx);
1436 SWAP!(e, inactive[i].Edge, inactive[j].Edge);
1437
1438 while {
1439 i = i + 1;
1440 inactive[i].Yx < median
1441 } {}
1442
1443 while {
1444 j = j - 1 ;
1445 inactive[j].Yx > median
1446 } {}
1447 }
1448
1449 SWAP!(y, inactive[f].Yx, inactive[j].Yx);
1450 SWAP!(e, inactive[f].Edge, inactive[j].Edge);
1451
1452 let a = j - f;
1453 let b = l - j;
1454
1455 // Use less stack space by recursing on the shorter subtable. Also,
1456 // have the less-overhead insertion-sort handle small subtables.
1457
1458 if (a <= b) {
1459 if (a > QUICKSORT_THRESHOLD as usize) {
1460 // 'a' is the smallest, so do it first:
1461
1462 QuickSortEdges(inactive, f, j - 1);
1463 QuickSortEdges(inactive, j + 1, l);
1464 } else if (b > QUICKSORT_THRESHOLD as usize) {
1465 QuickSortEdges(inactive, j + 1, l);
1466 }
1467 } else {
1468 if (b > QUICKSORT_THRESHOLD as usize) {
1469 // 'b' is the smallest, so do it first:
1470
1471 QuickSortEdges(inactive, j + 1 , l);
1472 QuickSortEdges(inactive, f, j + 1);
1473 } else if (a > QUICKSORT_THRESHOLD as usize) {
1474 QuickSortEdges(inactive, f, j -1);
1475 }
1476 }
1477 }
1478
1479 /**************************************************************************\
1480 *
1481 * Function Description:
1482 *
1483 * Do a sort of the inactive table using an insertion-sort. Expects
1484 * large tables to have already been sorted via quick-sort.
1485 *
1486 * Created:
1487 *
1488 * 03/25/2000 andrewgo
1489 *
1490 \**************************************************************************/
1491
1492 fn InsertionSortEdges(
1493 /* __inout_xcount(count forward & -1 back)*/ mut inactive: &mut [CInactiveEdge],
1494 mut count: INT,
1495 ) {
1496 let mut e: Ref<CEdge>;
1497 let mut y: LONGLONG;
1498 let mut yPrevious: LONGLONG;
1499
1500 assert!(inactive[0].Yx == i64::MIN);
1501 assert!(count >= 2);
1502 //inactive = &mut inactive[1..];
1503
1504 let mut indx = 2; // Skip first entry (by definition it's already in order!)
1505 count -= 1;
1506
1507 while {
1508 let mut p = indx;
1509
1510 // Copy the current stuff to temporary variables to make a hole:
1511
1512 e = (inactive[indx]).Edge;
1513 y = (inactive[indx]).Yx;
1514
1515 // Shift everything one slot to the right (effectively moving
1516 // the hole one position to the left):
1517
1518 while (y < {yPrevious = inactive[p-1].Yx; yPrevious}) {
1519 inactive[p].Yx = yPrevious;
1520 inactive[p].Edge = inactive[p-1].Edge;
1521 p -= 1;
1522 }
1523
1524 // Drop the temporary stuff into the final hole:
1525
1526 inactive[p].Yx = y;
1527 inactive[p].Edge = e;
1528
1529 // The quicksort should have ensured that we don't have to move
1530 // any entry terribly far:
1531
1532 assert!((indx - p) <= QUICKSORT_THRESHOLD as usize);
1533
1534 indx += 1;
1535 count -= 1;
1536 count != 0
1537 } {}
1538 }
1539
1540 /**************************************************************************\
1541 *
1542 * Function Description:
1543 *
1544 * Assert the state of the inactive array.
1545 *
1546 * Created:
1547 *
1548 * 03/25/2000 andrewgo
1549 *
1550 \**************************************************************************/
1551 macro_rules! ASSERTINACTIVEARRAY {
1552 ($inactive: expr, $count: expr) => {
1553 #[cfg(debug_assertions)]
1554 AssertInactiveArray($inactive, $count);
1555 };
1556 }
1557 fn AssertInactiveArray(
1558 /*__in_ecount(count)*/
1559 mut inactive: &[CInactiveEdge], // Annotation should allow the -1 element
1560 mut count: INT,
1561 ) {
1562 // Verify the head:
1563
1564 /*#if !ANALYSIS*/
1565 // #if needed because prefast don't know that the -1 element is avaliable
1566 assert!(inactive[0].Yx == i64::MIN);
1567 /*#endif*/
1568 assert!(inactive[1].Yx != i64::MIN);
1569
1570 while {
1571 let mut yx: LONGLONG = 0;
1572 YX((*inactive[1].Edge).X.get(), (*inactive[1].Edge).StartY, &mut yx);
1573
1574 assert!(inactive[1].Yx == yx);
1575 /*#if !ANALYSIS*/
1576 // #if needed because tools don't know that the -1 element is avaliable
1577 assert!(inactive[1].Yx >= inactive[0].Yx);
1578 /*#endif*/
1579 inactive = &inactive[1..];
1580 count -= 1;
1581 count != 0
1582 } {}
1583
1584 // Verify that the tail is setup appropriately:
1585
1586 assert!((*inactive[1].Edge).StartY == INT::MAX);
1587 }
1588
1589 /**************************************************************************\
1590 *
1591 * Function Description:
1592 *
1593 * Initialize and sort the inactive array.
1594 *
1595 * Returns:
1596 *
1597 * 'y' value of topmost edge.
1598 *
1599 * Created:
1600 *
1601 * 03/25/2000 andrewgo
1602 *
1603 \**************************************************************************/
1604
1605 pub fn InitializeInactiveArray<'a>(
1606 pEdgeStore: &'a Arena<CEdge<'a>>,
1607 /*__in_ecount(count+2)*/ rgInactiveArray: &mut [CInactiveEdge<'a>],
1608 count: UINT,
1609 tailEdge: Ref<'a, CEdge<'a>> // Tail sentinel for inactive list
1610 ) -> INT {
1611 let rgInactiveArrayPtr = rgInactiveArray.as_mut_ptr();
1612
1613 // First initialize the inactive array. Skip the first entry,
1614 // which we reserve as a head sentinel for the insertion sort:
1615
1616 let mut pInactiveEdge = &mut rgInactiveArray[1..];
1617
1618 for e in pEdgeStore.iter() {
1619
1620 pInactiveEdge[0].Edge = Ref::new(e);
1621 YX(e.X.get(), e.StartY, &mut pInactiveEdge[0].Yx);
1622 pInactiveEdge = &mut pInactiveEdge[1..];
1623 }
1624
1625 assert!(unsafe { pInactiveEdge.as_mut_ptr().offset_from(rgInactiveArrayPtr) } as UINT == count + 1);
1626
1627 // Add the tail, which is used when reading back the array. This
1628 // is why we had to allocate the array as 'count + 1':
1629
1630 pInactiveEdge[0].Edge = tailEdge;
1631
1632 // Add the head, which is used for the insertion sort. This is why
1633 // we had to allocate the array as 'count + 2':
1634
1635 rgInactiveArray[0].Yx = i64::MIN;
1636
1637 // Only invoke the quicksort routine if it's worth the overhead:
1638
1639 if (count as isize > QUICKSORT_THRESHOLD) {
1640 // Quick-sort this, skipping the first and last elements,
1641 // which are sentinels.
1642 //
1643 // We do 'inactiveArray + count' to be inclusive of the last
1644 // element:
1645
1646 QuickSortEdges(rgInactiveArray, 1, count as usize);
1647 }
1648
1649 // Do a quick sort to handle the mostly sorted result:
1650
1651 InsertionSortEdges(rgInactiveArray, count as i32);
1652
1653 ASSERTINACTIVEARRAY!(rgInactiveArray, count as i32);
1654
1655 // Return the 'y' value of the topmost edge:
1656
1657 return (*rgInactiveArray[1].Edge).StartY;
1658
1659 }
1660
1661 /**************************************************************************\
1662 *
1663 * Function Description:
1664 *
1665 * Insert edges into the active edge list.
1666 *
1667 * Created:
1668 *
1669 * 03/25/2000 andrewgo
1670 *
1671 \**************************************************************************/
1672
1673 pub fn InsertNewEdges<'a>(
1674 mut pActiveList: Ref<'a, CEdge<'a>>,
1675 iCurrentY: INT,
1676 /*__deref_inout_xcount(array terminated by an edge with StartY != iCurrentY)*/
1677 ppInactiveEdge: &'a mut [CInactiveEdge<'a>],
1678 pYNextInactive: &mut INT, // will be INT_MAX when no more
1679 ) -> &'a mut [CInactiveEdge<'a>] {
1680
1681 let mut inactive: &mut [CInactiveEdge] = ppInactiveEdge;
1682
1683 assert!((*inactive[0].Edge).StartY == iCurrentY);
1684
1685 while {
1686 let newActive: Ref<CEdge> = inactive[0].Edge;
1687
1688 // The activeList edge list sentinel has X = INT_MAX, so this always
1689 // terminates:
1690
1691 while ((*(*pActiveList).Next.get()).X < (*newActive).X) {
1692 pActiveList = (*pActiveList).Next.get();
1693 }
1694
1695 if SORT_EDGES_INCLUDING_SLOPE {
1696 // The activeList edge list sentinel has Dx = INT_MAX, so this always
1697 // terminates:
1698
1699 while (((*(*pActiveList).Next.get()).X == (*newActive).X) && ((*(*pActiveList).Next.get()).Dx < (*newActive).Dx)) {
1700 pActiveList = (*pActiveList).Next.get();
1701 }
1702 }
1703
1704 (*newActive).Next.set((*pActiveList).Next.get());
1705 (*pActiveList).Next.set(newActive);
1706
1707 inactive = &mut inactive[1..];
1708 (*(inactive[0]).Edge).StartY == iCurrentY
1709 } {}
1710
1711 *pYNextInactive = (*(inactive[0]).Edge).StartY;
1712 return inactive;
1713
1714 }
1715
1716 /**************************************************************************\
1717 *
1718 * Function Description:
1719 *
1720 * Sort the edges so that they're in ascending 'x' order.
1721 *
1722 * We use a bubble-sort for this stage, because edges maintain good
1723 * locality and don't often switch ordering positions.
1724 *
1725 * Created:
1726 *
1727 * 03/25/2000 andrewgo
1728 *
1729 \**************************************************************************/
1730
1731 fn SortActiveEdges(list: Ref<CEdge>) {
1732
1733 let mut swapOccurred: bool;
1734 let mut tmp: Ref<CEdge>;
1735
1736 // We should never be called with an empty active edge list:
1737
1738 assert!((*(*list).Next.get()).X.get() != INT::MAX);
1739
1740 while {
1741 swapOccurred = false;
1742
1743 let mut previous = list;
1744 let mut current = (*list).Next.get();
1745 let mut next = (*current).Next.get();
1746 let mut nextX = (*next).X.get();
1747
1748 while {
1749 if (nextX < (*current).X.get()) {
1750 swapOccurred = true;
1751
1752 (*previous).Next.set(next);
1753 (*current).Next.set((*next).Next.get());
1754 (*next).Next.set(current);
1755
1756 SWAP!(tmp, next, current);
1757 }
1758
1759 previous = current;
1760 current = next;
1761 next = (*next).Next.get();
1762 nextX = (*next).X.get();
1763 nextX != INT::MAX
1764 } {}
1765 swapOccurred
1766 } {}
1767
1768 }