├── .editorconfig ├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── bin └── package.sh ├── package.json ├── serverless.kyle.yml ├── serverless.yml ├── serverless_slope ├── __init__.py ├── app.py ├── convert.py ├── hillshade.py └── util.py ├── setup.py └── site ├── .gitignore ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg ├── serviceWorker.js └── setupTests.js └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | end_of_line = lf 9 | insert_final_newline = true 10 | charset = utf-8 11 | indent_style = space 12 | indent_size = 4 13 | 14 | [*.{js,yml}] 15 | indent_size = 2 16 | 17 | # Tab indentation (no size specified) 18 | [Makefile] 19 | indent_style = tab 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .serverless 2 | package.zip 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | pip-wheel-metadata/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | target/ 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 88 | .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "10" 4 | branches: 5 | except: 6 | # Built website 7 | - gh_pages 8 | deploy: 9 | provider: script 10 | script: cd site && yarn install && yarn run deploy 11 | skip_cleanup: true 12 | on: 13 | branch: master 14 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM lambci/lambda:build-python3.8 2 | 3 | WORKDIR /tmp 4 | 5 | ENV PYTHONUSERBASE=/var/task 6 | 7 | COPY serverless_slope/ serverless_slope/ 8 | COPY README.md README.md 9 | COPY setup.py setup.py 10 | 11 | # Install dependencies 12 | RUN pip install . --user 13 | RUN rm -rf serverless_slope setup.py 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kyle Barron 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | SHELL = /bin/bash 3 | 4 | package: 5 | docker build --tag serverless-slope:latest . 6 | docker run --name serverless-slope --volume $(shell pwd)/:/local -itd serverless-slope:latest bash 7 | docker exec -it serverless-slope bash '/local/bin/package.sh' 8 | docker stop serverless-slope 9 | docker rm serverless-slope 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serverless-slope 2 | 3 | Serverless, worldwide slope angle shading tiles generated from [AWS Terrain 4 | Tiles](https://registry.opendata.aws/terrain-tiles/). 5 | 6 | **NOTE**: I think I currently have some z-scaling issues, because the generated 7 | tiles indicate lesser slopes than [another project](https://nst.guide) (turn on 8 | slope-angle shading) which uses precomputed tiles from `gdaldem`. 9 | 10 | ## Motivation 11 | 12 | One of the many great AWS Open Data datasets is [terrain 13 | tiles](https://registry.opendata.aws/terrain-tiles/). These are a collection of 14 | worldwide elevation products stored on AWS S3 for anyone to use. This project 15 | shows how easy, fast, and cheap it is to leverage AWS Open Data for hobby 16 | projects. 17 | 18 | Slope-angle shading is a great overlay for many types of outdoor planning. The 19 | darker the colors, the steeper the slope, the more you need to make sure you're 20 | prepared. 21 | 22 | This uses [Caltopo's](https://caltopo.com) slope-angle shading color scheme by 23 | default, but it's trivial to supply a different set of RGB values to make a 24 | different color scheme. 25 | 26 | ## Deploy 27 | 28 | Deployment should be easy and fast. This requires Docker, Python, and Node: 29 | 30 | ```bash 31 | git clone https://github.com/kylebarron/serverless-slope 32 | cd serverless-slope 33 | make package 34 | npm i -g serverless 35 | sls deploy --bucket bucket-where-you-store-data --cache-control "public,max-age=4000" 36 | ``` 37 | 38 | ## Pricing 39 | 40 | Roughly ~$5.70 per 1M requests. Note this is for requests _that reach Lambda_. 41 | By using Cloudflare and an appropriate cache control header, this could be 42 | substantially reduced. 43 | 44 | Lambda: 45 | 46 | - $0.20 per 1M requests 47 | - Set to 192MB and if each invocation takes .9s, per 1M requests: 48 | 49 | $0.0000166667 GB-second / * 192 / 1024 * .9 * 1M = $2.81 50 | 51 | API Gateway: 52 | 53 | - $1.00 per 1M requests 54 | 55 | Data Transfer: 56 | 57 | 20 KB * 1M / 1024 / 1024 * $0.09 = $1.70 58 | 59 | ### Ways to lower prices: 60 | 61 | - Use Cloudflare to cache images with a long cache control header 62 | 63 | ### Hosted comparison 64 | 65 | At zoom 15, there are 4^15 ~= 1 Billion tiles to cover the globe. At 10KB per 66 | tile, that would be 10TB of data, or $235/month _just to store on S3_. Obviously 67 | much of the globe is water, so you could be smarter and not store non-land 68 | tiles, but it's not going to be as cheap for low to mid-range use as serverless 69 | is. 70 | -------------------------------------------------------------------------------- /bin/package.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "-----------------------" 3 | echo "Creating lambda package" 4 | echo "-----------------------" 5 | echo "Remove uncompiled python scripts" 6 | # Leave module precompiles for faster Lambda startup 7 | cd ${PYTHONUSERBASE}/lib/python*/site-packages/ 8 | find . -type f -name '*.pyc' | while read f; do n=$(echo $f | sed 's/__pycache__\///' | sed 's/.cpython-[2-3][0-9]//'); cp $f $n; done; 9 | find . -type d -a -name '__pycache__' -print0 | xargs -0 rm -rf 10 | find . -type f -a -name '*.py' -print0 | xargs -0 rm -f 11 | 12 | echo "Create archive" 13 | zip -r9q /tmp/package.zip * 14 | 15 | cp /tmp/package.zip /local/package.zip 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "serverless-slope", 3 | "version": "0.1.0", 4 | "description": "Serverless, worldwide slope angle shading tiles.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"no test specified\"" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/kylebarron/serverless-slope.git" 12 | }, 13 | "author": "", 14 | "license": "MIT", 15 | "bugs": { 16 | "url": "https://github.com/kylebarron/serverless-slope/issues" 17 | }, 18 | "homepage": "https://github.com/kylebarron/serverless-slope#readme" 19 | } 20 | -------------------------------------------------------------------------------- /serverless.kyle.yml: -------------------------------------------------------------------------------- 1 | service: serverless-slope 2 | 3 | provider: 4 | name: aws 5 | runtime: python3.8 6 | stage: ${opt:stage, 'production'} 7 | region: ${opt:region, 'us-east-1'} 8 | deploymentBucket: ${opt:bucket} 9 | httpApi: 10 | cors: 11 | allowedOrigins: 12 | - http://localhost 13 | - https://all-transit.com 14 | - https://kylebarron.dev 15 | - https://kylebarron.github.io 16 | - https://landsat3d.com 17 | - https://landsat8.earth 18 | - https://nst.guide 19 | - https://nstguide.com 20 | - https://sentine2.earth 21 | - https://trails3d.com 22 | allowedHeaders: 23 | - Authorization 24 | - Content-Type 25 | - X-Amz-Date 26 | - X-Amz-Security-Token 27 | - X-Amz-User-Agent 28 | - X-Api-Key 29 | allowedMethods: 30 | - GET 31 | - OPTIONS 32 | allowCredentials: true 33 | maxAge: 6000 # In seconds 34 | 35 | iamRoleStatements: 36 | - Effect: "Allow" 37 | Action: 38 | - "*" 39 | Resource: 40 | - arn:aws:s3:::${opt:bucket}* 41 | 42 | - Effect: "Allow" 43 | Action: 44 | - "s3:*" 45 | Resource: 46 | - "arn:aws:s3:::elevation-tiles-prod*" 47 | 48 | apiGateway: 49 | binaryMediaTypes: 50 | - '*/*' 51 | minimumCompressionSize: 1 52 | 53 | package: 54 | artifact: package.zip 55 | 56 | functions: 57 | app: 58 | handler: serverless_slope.app.app 59 | memorySize: 192 60 | timeout: 10 61 | environment: 62 | CACHE_CONTROL: ${opt:cache-control, 'public,max-age=3600'} 63 | 64 | events: 65 | - httpApi: 66 | path: /{proxy+} 67 | method: '*' 68 | -------------------------------------------------------------------------------- /serverless.yml: -------------------------------------------------------------------------------- 1 | service: serverless-slope 2 | 3 | provider: 4 | name: aws 5 | runtime: python3.8 6 | stage: ${opt:stage, 'production'} 7 | region: ${opt:region, 'us-east-1'} 8 | deploymentBucket: ${opt:bucket} 9 | httpApi: 10 | cors: true 11 | 12 | iamRoleStatements: 13 | - Effect: "Allow" 14 | Action: 15 | - "*" 16 | Resource: 17 | - arn:aws:s3:::${opt:bucket}* 18 | 19 | - Effect: "Allow" 20 | Action: 21 | - "s3:*" 22 | Resource: 23 | - "arn:aws:s3:::elevation-tiles-prod*" 24 | 25 | apiGateway: 26 | binaryMediaTypes: 27 | - '*/*' 28 | minimumCompressionSize: 1 29 | 30 | package: 31 | artifact: package.zip 32 | 33 | functions: 34 | app: 35 | handler: serverless_slope.app.app 36 | memorySize: 192 37 | timeout: 10 38 | environment: 39 | CACHE_CONTROL: ${opt:cache-control, 'public,max-age=3600'} 40 | 41 | events: 42 | - httpApi: 43 | path: /{proxy+} 44 | method: '*' 45 | -------------------------------------------------------------------------------- /serverless_slope/__init__.py: -------------------------------------------------------------------------------- 1 | """Top-level package for serverless-slope.""" 2 | 3 | __author__ = """Kyle Barron""" 4 | __version__ = '0.1.0' 5 | -------------------------------------------------------------------------------- /serverless_slope/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | from typing import BinaryIO, Tuple 3 | 4 | from boto3.session import Session as boto3_session 5 | from imageio import imread 6 | 7 | from lambda_proxy.proxy import API 8 | from serverless_slope.convert import normals_to_colormap 9 | from serverless_slope.hillshade import hillshade 10 | from serverless_slope.util import array_to_image 11 | 12 | session = boto3_session() 13 | s3_client = session.client("s3") 14 | 15 | app = API(name="serverless-slope") 16 | 17 | 18 | @app.route( 19 | "/slope///.png", 20 | methods=["GET"], 21 | payload_compression_method="gzip", 22 | binary_b64encode=True, 23 | cache_control = os.getenv('CACHE_CONTROL'), 24 | tag=["tiles"]) 25 | def _img(z: int = None, x: int = None, y: int = None, 26 | **kwargs) -> Tuple[str, str, BinaryIO]: 27 | """Handle tile requests.""" 28 | key = f'normal/{z}/{x}/{y}.png' 29 | obj = s3_client.get_object(Bucket='elevation-tiles-prod', Key=key) 30 | 31 | if obj['ResponseMetadata']['HTTPStatusCode'] != 200: 32 | return ("EMPTY", "text/plain", "empty tiles") 33 | 34 | normals = imread(obj['Body'].read()) 35 | rgba = normals_to_colormap(normals) 36 | return ("OK", "image/png", array_to_image(rgba)) 37 | 38 | 39 | @app.route( 40 | "/hillshade///.png", 41 | methods=["GET"], 42 | payload_compression_method="gzip", 43 | binary_b64encode=True, 44 | cache_control = os.getenv('CACHE_CONTROL'), 45 | tag=["tiles"]) 46 | def _img(z: int = None, x: int = None, y: int = None, 47 | **kwargs) -> Tuple[str, str, BinaryIO]: 48 | """Handle tile requests.""" 49 | key = f'normal/{z}/{x}/{y}.png' 50 | obj = s3_client.get_object(Bucket='elevation-tiles-prod', Key=key) 51 | 52 | if obj['ResponseMetadata']['HTTPStatusCode'] != 200: 53 | return ("EMPTY", "text/plain", "empty tiles") 54 | 55 | normals = imread(obj['Body'].read()) 56 | intensity = hillshade(normals, **kwargs) 57 | 58 | return ("OK", "image/png", array_to_image(intensity)) 59 | 60 | 61 | @app.route("/favicon.ico", methods=["GET"], cors=True, tag=["other"]) 62 | def favicon() -> Tuple[str, str, str]: 63 | """Favicon.""" 64 | return ("EMPTY", "text/plain", "") 65 | -------------------------------------------------------------------------------- /serverless_slope/convert.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import numpy as np 4 | 5 | BINS = [26.5, 29.5, 31.5, 34.5, 45.5, 50.5, 59.5] 6 | COLORMAP = [[255, 255, 255, 0], [248, 253, 85, 255], [241, 184, 64, 255], 7 | [238, 128, 49, 255], [235, 51, 35, 255], [122, 41, 217, 255], 8 | [0, 38, 245, 255], [0, 0, 0, 255]] 9 | 10 | 11 | # https://github.com/tilezen/joerd/blob/0b86765156d0612d837548c2cf70376c43b3405c/joerd/output/normal.py#L26-L41 12 | def _generate_mapping_table(): 13 | table = [] 14 | for i in range(0, 11): 15 | table.append(-11000 + i * 1000) 16 | table.append(-100) 17 | table.append(-50) 18 | table.append(-20) 19 | table.append(-10) 20 | table.append(-1) 21 | for i in range(0, 150): 22 | table.append(20 * i) 23 | for i in range(0, 60): 24 | table.append(3000 + 50 * i) 25 | for i in range(0, 29): 26 | table.append(6000 + 100 * i) 27 | return table 28 | 29 | 30 | # Make a constant version of the table for reference. 31 | HEIGHT_TABLE = _generate_mapping_table() 32 | 33 | 34 | def get_elevation(h: int): 35 | if h == 255: 36 | h -= 1 37 | 38 | return HEIGHT_TABLE[255 - h] 39 | 40 | 41 | def normals_to_colormap( 42 | normals: np.ndarray, bins=BINS, colormap=COLORMAP) -> bytes: 43 | """Convert png of normals to png of colormap 44 | 45 | Args: 46 | - normals: 256x256x4 array of normals 47 | 48 | Returns: 49 | - rgba pixels in 256x256x4 ndarray 50 | """ 51 | # Get slope data 52 | slope = get_slope(normals) 53 | 54 | # Get mask of areas below 0 elevation 55 | mask = below_sea_level_mask(normals[:, :, 3]) 56 | 57 | # Apply colormap and convert to rgba 58 | return apply_colormap(slope, mask, bins=bins, colormap=colormap) 59 | 60 | 61 | def get_slope(arr: np.array) -> np.array: 62 | """Compute slope array from 4d array of normals 63 | """ 64 | # https://github.com/tilezen/joerd/blob/0b86765156d0612d837548c2cf70376c43b3405c/joerd/output/normal.py#L176-L179 65 | # Note that because of rounding necessary to encode as 8-bit ints, the 66 | # unscaled vector lengths don't add up exactly to 1 67 | unscaled_z = (arr[:, :, 2] / 128) - 1 68 | 69 | # To find the slope, you want the angle between the normal vector and a 70 | # vector straight up from a horizontal surface. Such a straight up vector is 71 | # <0, 0, 1>. 72 | # Then the angle between two vectors is defined as 73 | # 74 | # A · B = |A| * |B| * cos(angle) 75 | # 76 | # Since A and B are unit vectors, |A| and |B| are 1. 77 | # A · B where B is <0, 0, 1> is equal to the z coord of A. 78 | # Then just take the arccos to find the angle. 79 | # 80 | # Finally, this angle is in radians, so convert to degrees 81 | # https://stackoverflow.com/a/16669463 82 | return np.degrees(np.arccos(unscaled_z)) 83 | np.arccosh 84 | 85 | 86 | def below_sea_level_mask(arr: np.array) -> np.array: 87 | """Create mask of pixels below sea level 88 | 89 | Args: 90 | - arr: array (256, 256) of quantized elevation values 91 | 92 | Returns: 93 | np.array (256, 256). True means <0 elevation 94 | """ 95 | # Vectorize function 96 | vfunc = np.vectorize(get_elevation) 97 | 98 | # Find quantized elevations 99 | ele = vfunc(arr) 100 | 101 | # Create mask 102 | return ele < 0 103 | 104 | 105 | def apply_colormap(slope, mask, bins, colormap): 106 | # Bin data 107 | inds = np.digitize(slope, bins) 108 | 109 | # Apply colormap, one at a time 110 | split = [dict(enumerate(map(lambda x: x[i], colormap))) for i in range(4)] 111 | arrs = [] 112 | for split_map in split: 113 | channel = np.vectorize(split_map.get)(inds) 114 | 115 | # Where the mask is True, set to 0 116 | # This includes all elevations <0 117 | np.putmask(channel, mask, 0) 118 | arrs.append(channel) 119 | 120 | return np.dstack(arrs) 121 | -------------------------------------------------------------------------------- /serverless_slope/hillshade.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def hillshade(normals: np.ndarray, azdeg=315, altdeg=45, fraction=1): 5 | """Compute raster hillshade from normals 6 | 7 | This is modified from 8 | https://github.com/openterrain/deploy/blob/ed01ec631b9d8c2757799d237f25b38b77a40b59/openterrain/__init__.py#L291-L354 9 | 10 | This is a slightly modified version of 11 | matplotlib.colors.LightSource.hillshade, modified to remove the contrast 12 | stretching (because that uses local min/max values). 13 | Calculates the illumination intensity for a surface using the defined 14 | azimuth and elevation for the light source. 15 | 16 | Imagine an artificial sun placed at infinity in some azimuth and 17 | elevation position illuminating our surface. The parts of the surface 18 | that slope toward the sun should brighten while those sides facing away 19 | should become darker. 20 | 21 | Parameters 22 | ---------- 23 | normals : array-like 24 | A 2d array (or equivalent) of the height values used to generate an 25 | illumination map 26 | azdeg : number, optional 27 | The azimuth (0-360, degrees clockwise from North) of the light 28 | source. Defaults to 315 degrees (from the northwest). 29 | altdeg : number, optional 30 | The altitude (0-90, degrees up from horizontal) of the light 31 | source. Defaults to 45 degrees from horizontal. 32 | fraction : number, optional 33 | Increases or decreases the contrast of the hillshade. Values 34 | greater than one will cause intermediate values to move closer to 35 | full illumination or shadow (and clipping any values that move 36 | beyond 0 or 1). Note that this is not visually or mathematically 37 | the same as vertical exaggeration. 38 | Returns 39 | ------- 40 | intensity : ndarray 41 | A 2d array of illumination values between 0-1, where 0 is 42 | completely in shadow and 1 is completely illuminated. 43 | """ 44 | # Rescale normals to be -1 to 1 45 | dx = (normals[:, :, 0] / 128) - 1 46 | dy = (normals[:, :, 1] / 128) - 1 47 | 48 | # Azimuth is in degrees clockwise from North. Convert to radians 49 | # counterclockwise from East (mathematical notation). 50 | az = np.radians(90 - azdeg) 51 | alt = np.radians(altdeg) 52 | 53 | # Calculate the intensity from the illumination angle 54 | aspect = np.arctan2(dy, dx) 55 | slope = 0.5 * np.pi - np.arctan(np.hypot(dx, dy)) 56 | intensity = ( 57 | np.sin(alt) * np.sin(slope) + 58 | np.cos(alt) * np.cos(slope) * np.cos(az - aspect)) 59 | 60 | # Apply contrast stretch 61 | intensity *= fraction 62 | 63 | intensity = np.clip(intensity, 0, 1, intensity) 64 | 65 | return intensity 66 | -------------------------------------------------------------------------------- /serverless_slope/util.py: -------------------------------------------------------------------------------- 1 | from io import BytesIO 2 | 3 | from imageio import imwrite 4 | 5 | 6 | def array_to_image(arr): 7 | new_buf = BytesIO() 8 | imwrite(new_buf, arr, format='png-pil', optimize=True) 9 | 10 | new_buf.seek(0) 11 | return new_buf.read() 12 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """The setup script.""" 3 | 4 | from setuptools import find_packages, setup 5 | 6 | with open('README.md') as f: 7 | readme = f.read() 8 | 9 | # Runtime requirements. 10 | inst_reqs = ["lambda-proxy>=5.1.1", "imageio", "numpy", "boto3"] 11 | setup_requirements = ['setuptools >= 38.6.0', 'twine >= 1.11.0'] 12 | 13 | # yapf: disable 14 | setup( 15 | author="Kyle Barron", 16 | author_email='kylebarron2@gmail.com', 17 | python_requires='>=3.6', 18 | classifiers=[ 19 | 'Development Status :: 4 - Beta', 20 | 'Intended Audience :: Developers', 21 | 'License :: OSI Approved :: MIT License', 22 | 'Natural Language :: English', 23 | 'Programming Language :: Python :: 3', 24 | 'Programming Language :: Python :: 3.6', 25 | 'Programming Language :: Python :: 3.7', 26 | 'Programming Language :: Python :: 3.8', 27 | ], 28 | description="Serverless, worldwide slope angle shading tiles", 29 | install_requires=inst_reqs, 30 | license="MIT license", 31 | long_description=readme, 32 | long_description_content_type='text/markdown', 33 | name='serverless-slope', 34 | packages=find_packages(include=['serverless_slope', 'serverless_slope.*']), 35 | setup_requires=setup_requirements, 36 | url='https://github.com/kylebarron/serverless-slope', 37 | version='0.1.0', 38 | zip_safe=False 39 | ) 40 | -------------------------------------------------------------------------------- /site/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /site/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `yarn start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `yarn test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `yarn build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `yarn eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `yarn build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /site/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "site", 3 | "version": "0.1.0", 4 | "private": true, 5 | "homepage": "https://kylebarron.dev/serverless-slope", 6 | "dependencies": { 7 | "@testing-library/jest-dom": "^4.2.4", 8 | "@testing-library/react": "^9.3.2", 9 | "@testing-library/user-event": "^7.1.2", 10 | "react": "^16.13.1", 11 | "react-dom": "^16.13.1", 12 | "react-map-gl": "^5.2.3", 13 | "react-scripts": "3.4.1" 14 | }, 15 | "scripts": { 16 | "start": "react-scripts start", 17 | "build": "react-scripts build", 18 | "test": "react-scripts test", 19 | "eject": "react-scripts eject", 20 | "deploy": "react-scripts build && gh-pages -d build -b gh-pages -r https://$GH_TOKEN@github.com/kylebarron/serverless-slope.git" 21 | }, 22 | "eslintConfig": { 23 | "extends": "react-app" 24 | }, 25 | "browserslist": { 26 | "production": [ 27 | ">0.2%", 28 | "not dead", 29 | "not op_mini all" 30 | ], 31 | "development": [ 32 | "last 1 chrome version", 33 | "last 1 firefox version", 34 | "last 1 safari version" 35 | ] 36 | }, 37 | "devDependencies": { 38 | "gh-pages": "^2.2.0" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /site/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kylebarron/serverless-slope/8465087778b2315a0a4ce01975c30466473a1c91/site/public/favicon.ico -------------------------------------------------------------------------------- /site/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /site/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kylebarron/serverless-slope/8465087778b2315a0a4ce01975c30466473a1c91/site/public/logo192.png -------------------------------------------------------------------------------- /site/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kylebarron/serverless-slope/8465087778b2315a0a4ce01975c30466473a1c91/site/public/logo512.png -------------------------------------------------------------------------------- /site/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /site/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /site/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /site/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import ReactMapGL, { Source, Layer } from "react-map-gl"; 3 | 4 | export default function Map() { 5 | const [viewport, setViewport] = useState({ 6 | width: "100vw", 7 | height: "100vh", 8 | latitude: 36.1284, 9 | longitude: -112.1861, 10 | zoom: 12 11 | }); 12 | 13 | return ( 14 | 20 | 30 | 38 | 39 | 40 | 50 | 55 | 56 | 57 | ); 58 | } 59 | -------------------------------------------------------------------------------- /site/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /site/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /site/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | // If you want your app to work offline and load faster, you can change 15 | // unregister() to register() below. Note this comes with some pitfalls. 16 | // Learn more about service workers: https://bit.ly/CRA-PWA 17 | serviceWorker.unregister(); 18 | -------------------------------------------------------------------------------- /site/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /site/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' }, 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready 134 | .then(registration => { 135 | registration.unregister(); 136 | }) 137 | .catch(error => { 138 | console.error(error.message); 139 | }); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /site/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | --------------------------------------------------------------------------------