{"id":157,"date":"2026-11-13T12:33:02","date_gmt":"2026-11-13T04:33:02","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-cohen-sutherland-clips-a-segment-with-outcodes\/"},"modified":"2026-11-13T21:51:29","modified_gmt":"2026-11-13T13:51:29","slug":"how-cohen-sutherland-clips-a-segment-with-outcodes","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-cohen-sutherland-clips-a-segment-with-outcodes\/","title":{"rendered":"How Cohen-Sutherland clips a segment with outcodes"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> The <strong>Cohen-Sutherland<\/strong> algorithm clips a line segment to an axis-aligned rectangle by assigning each endpoint a 4-bit <strong>outcode<\/strong>. The bits say above, below, left, and right. If both codes are zero, the segment is inside. If the bitwise AND of the codes is nonzero, both endpoints share a half-plane and the segment is outside. Otherwise an endpoint that is outside is replaced by the intersection with the corresponding boundary, and the codes are recomputed. The loop is constant time for a rectangle.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">A segment against a rectangle has a small set of outcomes: both ends inside, both ends in the same exterior half-plane, or a crossing that must be cut. The outcode packages the four half-plane tests so the two trivial outcomes are bit operations. Only the crossing case does arithmetic, and it does it one boundary at a time.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The intersection with a vertical or horizontal boundary is a linear interpolation of the endpoint coordinates. Using the wrong boundary bit, or updating only one coordinate, leaves the point outside and the loop can spin if the code is not recomputed from the new point.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The algorithm returns the clipped segment inside the closed rectangle, or reports that the segment misses it. Each iteration brings at least one endpoint onto a boundary or rejects the segment, so the loop ends in a handful of steps. Extra memory is the two outcodes. The rectangle is axis-aligned. A rotated rectangle or a convex polygon needs a different clipper, such as Sutherland-Hodgman or Cyrus-Beck.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The trivial reject is the AND of the codes, not the OR. The OR is nonzero when any endpoint is outside, which includes segments that cross the rectangle and must be kept. Confusing AND with OR rejects visible segments.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Compute the outcode of an endpoint: set the left bit if x is less than xmin, the right bit if x is greater than xmax, the bottom bit if y is less than ymin, and the top bit if y is greater than ymax.<\/li>\n<li>If code0 OR code1 is zero, both ends are inside. Accept the segment.<\/li>\n<li>If code0 AND code1 is nonzero, reject the segment. Both ends are outside the same boundary.<\/li>\n<li>Otherwise pick an endpoint whose code is nonzero. Choose one set bit and replace that endpoint by the intersection with the corresponding edge of the rectangle.<\/li>\n<li>Recompute that endpoint&#8217;s code and repeat. When the loop accepts, the current endpoints are the clipped segment.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The bit tests are for an axis-aligned box. They do not clip to a triangle. The trivial reject is a shared outside half-plane. A segment that crosses a corner may take two iterations, one per boundary, and both are required. The geometric intersection is exact for that rectangle. Raster clipping of pixels is Bresenham after this geometric clip, not instead of it.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the trivial reject uses the OR of the outcodes<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Reject when the OR is nonzero<\/td>\n<td>Any segment with one end outside has a nonzero OR, including segments that enter the rectangle. The reject test is the AND, which means a shared outside region.<\/td>\n<\/tr>\n<tr>\n<td>Update the endpoint and keep the old outcode<\/td>\n<td>The next test sees a stale half-plane and can choose the same boundary again. Recompute the code from the new coordinates.<\/td>\n<\/tr>\n<tr>\n<td>Clip to a rotated rectangle with the same four bits<\/td>\n<td>The half-planes are no longer the coordinate inequalities. The outcodes do not describe that rectangle.<\/td>\n<\/tr>\n<tr>\n<td>Interpolate the wrong axis against a vertical edge<\/td>\n<td>A vertical edge fixes x and solves for y. Swapping the interpolation leaves the point off the edge and the loop does not converge.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Pixel selection after the clip is Bresenham. A general convex polygon clip is Sutherland-Hodgman. Cohen-Sutherland is the axis-aligned outcode clip.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment clips a segment to an axis-aligned window with 4-bit outcodes. A segment is accepted when the OR of the codes is 0 and rejected when the AND is nonzero. The segment from (-1, 1) to (4, 1) against the window [0, 3] \u00d7 [0, 3] becomes <code>(0, 1)-(3, 1)<\/code>.<\/p>\n\n<pre><code class=\"language-python\">INSIDE, LEFT, RIGHT, BOTTOM, TOP = 0, 1, 2, 4, 8\nxmin, xmax, ymin, ymax = 0, 3, 0, 3\n\ndef code(x, y):\n    c = INSIDE\n    if x &lt; xmin:\n        c |= LEFT\n    elif x &gt; xmax:\n        c |= RIGHT\n    if y &lt; ymin:\n        c |= BOTTOM\n    elif y &gt; ymax:\n        c |= TOP\n    return c\n\ndef clip(x0, y0, x1, y1):\n    c0, c1 = code(x0, y0), code(x1, y1)\n    while True:\n        if c0 | c1 == 0:\n            return (x0, y0, x1, y1)\n        if c0 &amp; c1:\n            return None\n        c = c0 or c1\n        if c &amp; TOP:\n            x = x0 + (x1 - x0) * (ymax - y0) \/ (y1 - y0)\n            y = ymax\n        elif c &amp; BOTTOM:\n            x = x0 + (x1 - x0) * (ymin - y0) \/ (y1 - y0)\n            y = ymin\n        elif c &amp; RIGHT:\n            y = y0 + (y1 - y0) * (xmax - x0) \/ (x1 - x0)\n            x = xmax\n        else:\n            y = y0 + (y1 - y0) * (xmin - x0) \/ (x1 - x0)\n            x = xmin\n        if c == c0:\n            x0, y0, c0 = x, y, code(x, y)\n        else:\n            x1, y1, c1 = x, y, code(x, y)\n\nclipped = clip(-1, 1, 4, 1)\nassert clipped == (0, 1, 3, 1)\nprint(f&quot;({clipped[0]:.0f}, {clipped[1]:.0f})-({clipped[2]:.0f}, {clipped[3]:.0f})&quot;)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><strong>Cohen-Sutherland<\/strong> clips a segment to a viewport with outcodes, which is the reject test in 2D graphics and CAD. A segment whose codes are both outside the same edge is discarded without an intersection. Liang-Barsky solves the same clip with a different test.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop the outcodes for a box the segment is already known to lie inside. Keep them when many segments must be rejected quickly against a screen or a viewport, and use AND for the trivial reject.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Cohen-Sutherland returns the four-bit outcode and the AND test that rejects a segment lying entirely to one side. <strong>Cohen-Sutherland clips a segment to an axis-aligned rectangle by outcodes, accepting when both codes are zero and rejecting when their bitwise AND is nonzero.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: The Cohen-Sutherland algorithm clips a line segment to an axis-aligned rectangle by assigning each endpoint a 4-bit outcode. The bits say above, below, left, and right. If both codes are zero, the segment is inside. If the bitwise AND of the codes is nonzero, both endpoints share&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,40],"tags":[],"class_list":["post-157","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-geometry"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/157","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=157"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/157\/revisions"}],"predecessor-version":[{"id":556,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/157\/revisions\/556"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=157"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=157"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=157"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}