\ctxlua{metapost.showlog=true}
\edef\N{128} % Maximum number of rectangles
\usemodule[graph]
\startMPinclusions[+]
	vardef f primary x = (x+2)*x*(x-1) enddef;
	ax:=-2; bx:=1;
	R:=2/(1+sqrt(5));
	M:=32;
	N:=\N;

	path q[];
	picture base;
	dx:=(bx-ax)/M;
	ay:=f(ax);
	by:=ay;
	for m=1 upto M:
		c:=f(ax+m*dx);
		ay:=min(ay,c);
		by:=max(by,c);
	endfor;
	path p;
	p:=(ax,f(ax)) for m=1 upto M: .. (ax+m*dx,f(ax+m*dx)) endfor;
	L:=length p;
	u:=216/(bx-ax);
	v:=216/(by-ay)*R;
	pair r,s,t;

	vardef base =
		draw p xscaled u yscaled v withcolor red; % Plot "f(x)"
		ay:=(ypart llcorner bbox currentpicture)/v;
		by:=(ypart urcorner bbox currentpicture)/v;
		currentpicture:=currentpicture shifted (-ax*u,-ay*v); % Shift for using graph package
		draw begingraph((bx-ax)*u,(by-ay)*v); % Draw the graph
			setrange(ax,ay,bx,by); % Set the range for the axes
		endgraph;
		currentpicture:=currentpicture shifted (ax*u,ay*v); % Shift for using graph package
	enddef;
\stopMPinclusions

\starttext
	\startMPpage
		base;
		draw (ax*u,ay*v)--(bx*u,ay*v)--(bx*u,by*v)--(ax*u,by*v)--cycle;
		dx:=ax*u-xpart llcorner bbox currentpicture; % Distance between ax and left edge of picture
		dy:=ay*v-ypart llcorner bbox currentpicture; % Distance between ay and bottom edge of picture
		q1:=(ax*u-dx,ay*v-dy)--(bx*u+dx,ay*v-dy)--(bx*u+dx,by*v+dy)--(ax*u-dx,by*v+dy)--cycle;
		W:=ceiling(xpart urcorner bbox currentpicture - xpart llcorner bbox currentpicture); % Width of picture
		H:=ceiling(ypart urcorner bbox currentpicture - ypart llcorner bbox currentpicture); % Heigh of picture
		setbounds currentpicture to q1; % "Center" picture by padding right and top
	\stopMPpage
	\dorecurse{\luaexpr{math.floor(math.log(\N)/math.log(2))+1}}{
		\edef\M{\luaexpr{math.floor(2^(\recurselevel-1)+0.5)}}
		\startMPpage
			M:=\M;
			for n=1 upto M: % Fill and draw M (number of subintervals) rectangles
				r:=point ((n-1)/M*L) of p; % Left endpoint
				s:=point ((n-1/2)/M*L) of p; % Right endpoint
				t:=point (n/M*L) of p; % Midpoint
				q2:=(xpart r,0)--(xpart t,0)--(xpart t,ypart s)--(xpart r,ypart s)--cycle; % The rectangle to fill and draw
				fill q2 xscaled u yscaled v withcolor (3/5,4/5,1); % Fill rectangle
				draw q2 xscaled u yscaled v withpen pencircle scaled 0.1; % Draw rectangle
			endfor;
			base; % Draw the function, box, ticks, and labels
			setbounds currentpicture to q1; % "Center" picture by padding right and top
		\stopMPpage
	}
\stoptext
